Current method and class name into logging; are these methods functionally equivalent?
In the test script below based on previous answers, all techniques provide the desired result of returning an informative message to the screen and a logging file.
Besides execution time which seems to be much slower for the inspect methods, I can't see any way to choose between these alternatives. Are there any hidden pitfalls in one or the other techniques? I'll be moving the project Python 3 in the future so something most forward-compatible would be better than something which is fastest now.
- f2: 2011 https://stackoverflow.com/a/5067654/3904031
- f3: 2015 https://stackoverflow.com/a/33159791/3904031
- g: 2013 https://stackoverflow.com/a/15725912/3904031
- h: 2015 https://stackoverflow.com/a/33162432/3904031
Results:
I am Bob, an instance of B, speaking from f1
I am Bob, an instance of B, speaking from f2
I am Bob, an instance of B, speaking from f3
I am Bob, an instance of B, speaking from f4
I am Bob, an instance of B, speaking from g
I am Bob, an instance of B, speaking from h
Script:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logfmt = "%(levelname)s - %(message)s"
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logfmt, filemode='w')
self.logger = logging.getLogger()
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def whoami(self):
return inspect.stack()[1][3]
def whosdaddy(self):
return inspect.stack()[2][3]
def who_i(self, i=None):
if i==None: i=1
return inspect.stack()[i][3]
def mee(self):
return inspect.stack()[1][3]
def f1(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.mee()))
print msg
self.logger.info(msg)
def f2(self): # 2011 https://stackoverflow.com/a/5067654/3904031
me = inspect.stack()[0][3]
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def f3(self): # 2015 https://stackoverflow.com/a/33159791/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.whoami()))
print msg
self.logger.info(msg)
def f4(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.who_i(1)))
print msg
self.logger.info(msg)
def g(self):
me = sys._getframe().f_code.co_name # 2013 https://stackoverflow.com/a/15725912/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def h(self):
frame = inspect.currentframe()
me = inspect.getframeinfo(frame).function # 2015 https://stackoverflow.com/a/33162432/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
for x in ['f1', 'f2', 'f3', 'f4', 'g', 'h']:
getattr(b, x)()
python python-3.x python-2.7
add a comment |
In the test script below based on previous answers, all techniques provide the desired result of returning an informative message to the screen and a logging file.
Besides execution time which seems to be much slower for the inspect methods, I can't see any way to choose between these alternatives. Are there any hidden pitfalls in one or the other techniques? I'll be moving the project Python 3 in the future so something most forward-compatible would be better than something which is fastest now.
- f2: 2011 https://stackoverflow.com/a/5067654/3904031
- f3: 2015 https://stackoverflow.com/a/33159791/3904031
- g: 2013 https://stackoverflow.com/a/15725912/3904031
- h: 2015 https://stackoverflow.com/a/33162432/3904031
Results:
I am Bob, an instance of B, speaking from f1
I am Bob, an instance of B, speaking from f2
I am Bob, an instance of B, speaking from f3
I am Bob, an instance of B, speaking from f4
I am Bob, an instance of B, speaking from g
I am Bob, an instance of B, speaking from h
Script:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logfmt = "%(levelname)s - %(message)s"
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logfmt, filemode='w')
self.logger = logging.getLogger()
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def whoami(self):
return inspect.stack()[1][3]
def whosdaddy(self):
return inspect.stack()[2][3]
def who_i(self, i=None):
if i==None: i=1
return inspect.stack()[i][3]
def mee(self):
return inspect.stack()[1][3]
def f1(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.mee()))
print msg
self.logger.info(msg)
def f2(self): # 2011 https://stackoverflow.com/a/5067654/3904031
me = inspect.stack()[0][3]
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def f3(self): # 2015 https://stackoverflow.com/a/33159791/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.whoami()))
print msg
self.logger.info(msg)
def f4(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.who_i(1)))
print msg
self.logger.info(msg)
def g(self):
me = sys._getframe().f_code.co_name # 2013 https://stackoverflow.com/a/15725912/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def h(self):
frame = inspect.currentframe()
me = inspect.getframeinfo(frame).function # 2015 https://stackoverflow.com/a/33162432/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
for x in ['f1', 'f2', 'f3', 'f4', 'g', 'h']:
getattr(b, x)()
python python-3.x python-2.7
add a comment |
In the test script below based on previous answers, all techniques provide the desired result of returning an informative message to the screen and a logging file.
Besides execution time which seems to be much slower for the inspect methods, I can't see any way to choose between these alternatives. Are there any hidden pitfalls in one or the other techniques? I'll be moving the project Python 3 in the future so something most forward-compatible would be better than something which is fastest now.
- f2: 2011 https://stackoverflow.com/a/5067654/3904031
- f3: 2015 https://stackoverflow.com/a/33159791/3904031
- g: 2013 https://stackoverflow.com/a/15725912/3904031
- h: 2015 https://stackoverflow.com/a/33162432/3904031
Results:
I am Bob, an instance of B, speaking from f1
I am Bob, an instance of B, speaking from f2
I am Bob, an instance of B, speaking from f3
I am Bob, an instance of B, speaking from f4
I am Bob, an instance of B, speaking from g
I am Bob, an instance of B, speaking from h
Script:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logfmt = "%(levelname)s - %(message)s"
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logfmt, filemode='w')
self.logger = logging.getLogger()
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def whoami(self):
return inspect.stack()[1][3]
def whosdaddy(self):
return inspect.stack()[2][3]
def who_i(self, i=None):
if i==None: i=1
return inspect.stack()[i][3]
def mee(self):
return inspect.stack()[1][3]
def f1(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.mee()))
print msg
self.logger.info(msg)
def f2(self): # 2011 https://stackoverflow.com/a/5067654/3904031
me = inspect.stack()[0][3]
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def f3(self): # 2015 https://stackoverflow.com/a/33159791/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.whoami()))
print msg
self.logger.info(msg)
def f4(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.who_i(1)))
print msg
self.logger.info(msg)
def g(self):
me = sys._getframe().f_code.co_name # 2013 https://stackoverflow.com/a/15725912/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def h(self):
frame = inspect.currentframe()
me = inspect.getframeinfo(frame).function # 2015 https://stackoverflow.com/a/33162432/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
for x in ['f1', 'f2', 'f3', 'f4', 'g', 'h']:
getattr(b, x)()
python python-3.x python-2.7
In the test script below based on previous answers, all techniques provide the desired result of returning an informative message to the screen and a logging file.
Besides execution time which seems to be much slower for the inspect methods, I can't see any way to choose between these alternatives. Are there any hidden pitfalls in one or the other techniques? I'll be moving the project Python 3 in the future so something most forward-compatible would be better than something which is fastest now.
- f2: 2011 https://stackoverflow.com/a/5067654/3904031
- f3: 2015 https://stackoverflow.com/a/33159791/3904031
- g: 2013 https://stackoverflow.com/a/15725912/3904031
- h: 2015 https://stackoverflow.com/a/33162432/3904031
Results:
I am Bob, an instance of B, speaking from f1
I am Bob, an instance of B, speaking from f2
I am Bob, an instance of B, speaking from f3
I am Bob, an instance of B, speaking from f4
I am Bob, an instance of B, speaking from g
I am Bob, an instance of B, speaking from h
Script:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logfmt = "%(levelname)s - %(message)s"
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logfmt, filemode='w')
self.logger = logging.getLogger()
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def whoami(self):
return inspect.stack()[1][3]
def whosdaddy(self):
return inspect.stack()[2][3]
def who_i(self, i=None):
if i==None: i=1
return inspect.stack()[i][3]
def mee(self):
return inspect.stack()[1][3]
def f1(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.mee()))
print msg
self.logger.info(msg)
def f2(self): # 2011 https://stackoverflow.com/a/5067654/3904031
me = inspect.stack()[0][3]
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def f3(self): # 2015 https://stackoverflow.com/a/33159791/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.whoami()))
print msg
self.logger.info(msg)
def f4(self):
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.who_i(1)))
print msg
self.logger.info(msg)
def g(self):
me = sys._getframe().f_code.co_name # 2013 https://stackoverflow.com/a/15725912/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
def h(self):
frame = inspect.currentframe()
me = inspect.getframeinfo(frame).function # 2015 https://stackoverflow.com/a/33162432/3904031
msg = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
print msg
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
for x in ['f1', 'f2', 'f3', 'f4', 'g', 'h']:
getattr(b, x)()
python python-3.x python-2.7
python python-3.x python-2.7
edited Nov 28 '18 at 10:21
uhoh
asked Nov 28 '18 at 10:12
uhohuhoh
1,49511041
1,49511041
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
This turns out to be an x/y problem. logging
seems to have all of the functionality that I need, per this answer.
By using the attribute %(funcName)s
in the format statement, the following script does everything without any need to look into the stack, including the echo to the console.
Documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes
I am Bob, an instance of B, speaking from i
from:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logformat = '%(message)s %(funcName)s '
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logformat, filemode='w')
self.logger = logging.getLogger()
console = logging.StreamHandler() # no more print statements, yay!
formatter = logging.Formatter(logformat)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def i(self):
msg = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
b.i()
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53516968%2fcurrent-method-and-class-name-into-logging-are-these-methods-functionally-equiv%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This turns out to be an x/y problem. logging
seems to have all of the functionality that I need, per this answer.
By using the attribute %(funcName)s
in the format statement, the following script does everything without any need to look into the stack, including the echo to the console.
Documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes
I am Bob, an instance of B, speaking from i
from:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logformat = '%(message)s %(funcName)s '
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logformat, filemode='w')
self.logger = logging.getLogger()
console = logging.StreamHandler() # no more print statements, yay!
formatter = logging.Formatter(logformat)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def i(self):
msg = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
b.i()
add a comment |
This turns out to be an x/y problem. logging
seems to have all of the functionality that I need, per this answer.
By using the attribute %(funcName)s
in the format statement, the following script does everything without any need to look into the stack, including the echo to the console.
Documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes
I am Bob, an instance of B, speaking from i
from:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logformat = '%(message)s %(funcName)s '
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logformat, filemode='w')
self.logger = logging.getLogger()
console = logging.StreamHandler() # no more print statements, yay!
formatter = logging.Formatter(logformat)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def i(self):
msg = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
b.i()
add a comment |
This turns out to be an x/y problem. logging
seems to have all of the functionality that I need, per this answer.
By using the attribute %(funcName)s
in the format statement, the following script does everything without any need to look into the stack, including the echo to the console.
Documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes
I am Bob, an instance of B, speaking from i
from:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logformat = '%(message)s %(funcName)s '
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logformat, filemode='w')
self.logger = logging.getLogger()
console = logging.StreamHandler() # no more print statements, yay!
formatter = logging.Formatter(logformat)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def i(self):
msg = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
b.i()
This turns out to be an x/y problem. logging
seems to have all of the functionality that I need, per this answer.
By using the attribute %(funcName)s
in the format statement, the following script does everything without any need to look into the stack, including the echo to the console.
Documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes
I am Bob, an instance of B, speaking from i
from:
class A(object):
def __init__(self):
self.cname = self.__class__.__name__
logformat = '%(message)s %(funcName)s '
logging.basicConfig(filename="logme.log", level=logging.DEBUG,
format=logformat, filemode='w')
self.logger = logging.getLogger()
console = logging.StreamHandler() # no more print statements, yay!
formatter = logging.Formatter(logformat)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
class B(A):
def __init__(self, name):
self.name = name
A.__init__(self)
def i(self):
msg = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
self.logger.info(msg)
import sys, inspect, logging
b = B('Bob')
b.i()
edited Nov 28 '18 at 14:59
answered Nov 28 '18 at 12:25
uhohuhoh
1,49511041
1,49511041
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53516968%2fcurrent-method-and-class-name-into-logging-are-these-methods-functionally-equiv%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown