Python: How to create and use a custom logger in python use logging module?
I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = logging.DEBUG by default my code fails to log the debug or info messages. Can someone point out the problem here.
import boto3
import logging
def get_logger(name=__name__, level=logging.DEBUG):
# Create log handler
logHandler = logging.StreamHandler()
logHandler.setLevel(level)
# Set handler format
logFormat = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%d-%b-%y")
logHandler.setFormatter(logFormat)
# Create logger
logger = logging.getLogger(name)
# Add handler to logger
logger.addHandler(logHandler)
# Stop propagating the log messages to root logger
# logger.propagate = False
return logger
def listBuckets():
logThis = get_logger(level=logging.DEBUG)
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
logThis.debug(msg='This message is from logger')
print(bucket.name)
listBuckets()
python python-3.x amazon-web-services logging amazon-s3
add a comment |
I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = logging.DEBUG by default my code fails to log the debug or info messages. Can someone point out the problem here.
import boto3
import logging
def get_logger(name=__name__, level=logging.DEBUG):
# Create log handler
logHandler = logging.StreamHandler()
logHandler.setLevel(level)
# Set handler format
logFormat = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%d-%b-%y")
logHandler.setFormatter(logFormat)
# Create logger
logger = logging.getLogger(name)
# Add handler to logger
logger.addHandler(logHandler)
# Stop propagating the log messages to root logger
# logger.propagate = False
return logger
def listBuckets():
logThis = get_logger(level=logging.DEBUG)
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
logThis.debug(msg='This message is from logger')
print(bucket.name)
listBuckets()
python python-3.x amazon-web-services logging amazon-s3
First, you are not usinglogThisvariable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable astypeis a keyword in Python.
– Ankit Jaiswal
Nov 26 '18 at 5:24
The default root level logger is set toWARNINGlevel.
– Ankit Jaiswal
Nov 26 '18 at 5:30
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49
add a comment |
I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = logging.DEBUG by default my code fails to log the debug or info messages. Can someone point out the problem here.
import boto3
import logging
def get_logger(name=__name__, level=logging.DEBUG):
# Create log handler
logHandler = logging.StreamHandler()
logHandler.setLevel(level)
# Set handler format
logFormat = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%d-%b-%y")
logHandler.setFormatter(logFormat)
# Create logger
logger = logging.getLogger(name)
# Add handler to logger
logger.addHandler(logHandler)
# Stop propagating the log messages to root logger
# logger.propagate = False
return logger
def listBuckets():
logThis = get_logger(level=logging.DEBUG)
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
logThis.debug(msg='This message is from logger')
print(bucket.name)
listBuckets()
python python-3.x amazon-web-services logging amazon-s3
I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = logging.DEBUG by default my code fails to log the debug or info messages. Can someone point out the problem here.
import boto3
import logging
def get_logger(name=__name__, level=logging.DEBUG):
# Create log handler
logHandler = logging.StreamHandler()
logHandler.setLevel(level)
# Set handler format
logFormat = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%d-%b-%y")
logHandler.setFormatter(logFormat)
# Create logger
logger = logging.getLogger(name)
# Add handler to logger
logger.addHandler(logHandler)
# Stop propagating the log messages to root logger
# logger.propagate = False
return logger
def listBuckets():
logThis = get_logger(level=logging.DEBUG)
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
logThis.debug(msg='This message is from logger')
print(bucket.name)
listBuckets()
python python-3.x amazon-web-services logging amazon-s3
python python-3.x amazon-web-services logging amazon-s3
edited Nov 26 '18 at 6:32
exan
asked Nov 26 '18 at 5:17
exanexan
675
675
First, you are not usinglogThisvariable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable astypeis a keyword in Python.
– Ankit Jaiswal
Nov 26 '18 at 5:24
The default root level logger is set toWARNINGlevel.
– Ankit Jaiswal
Nov 26 '18 at 5:30
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49
add a comment |
First, you are not usinglogThisvariable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable astypeis a keyword in Python.
– Ankit Jaiswal
Nov 26 '18 at 5:24
The default root level logger is set toWARNINGlevel.
– Ankit Jaiswal
Nov 26 '18 at 5:30
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49
First, you are not using
logThis variable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable as type is a keyword in Python.– Ankit Jaiswal
Nov 26 '18 at 5:24
First, you are not using
logThis variable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable as type is a keyword in Python.– Ankit Jaiswal
Nov 26 '18 at 5:24
The default root level logger is set to
WARNING level.– Ankit Jaiswal
Nov 26 '18 at 5:30
The default root level logger is set to
WARNING level.– Ankit Jaiswal
Nov 26 '18 at 5:30
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49
add a comment |
2 Answers
2
active
oldest
votes
A couple of points to know (Read these logging docs for details)
- A parent's / ancestor's log level takes precedence while evaluating the effective log level
- A root logger, for example that created with getLogger, has WARNING as it default log level
You have set the log level of the handler (logHandler) but not the root (logger). At this point, no handler can have a log level less than the root's, ie, WARNING
logHandler.setLevel(level)
logger.addHandler(logHandler)
logThis.debug(msg='This message is from logger') # Does not log
logThis.warn(msg='This message is from logger') # Logs
So, set the root level to something reasonable and you should be good to go
logHandler.setLevel('WARNING') # or NOTSET
logThis.debug(msg='This message is from logger') # Logs!
add a comment |
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.
The docs state:
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger).
So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler.
Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...
... until either an ancestor with a level other than NOTSET is found, or
the root is reached.
[...]
If the root is reached, and it has a level of NOTSET, then all
messages will be processed. Otherwise, the root’s level will be used
as the effective level.
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default.
You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.
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%2f53475104%2fpython-how-to-create-and-use-a-custom-logger-in-python-use-logging-module%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
A couple of points to know (Read these logging docs for details)
- A parent's / ancestor's log level takes precedence while evaluating the effective log level
- A root logger, for example that created with getLogger, has WARNING as it default log level
You have set the log level of the handler (logHandler) but not the root (logger). At this point, no handler can have a log level less than the root's, ie, WARNING
logHandler.setLevel(level)
logger.addHandler(logHandler)
logThis.debug(msg='This message is from logger') # Does not log
logThis.warn(msg='This message is from logger') # Logs
So, set the root level to something reasonable and you should be good to go
logHandler.setLevel('WARNING') # or NOTSET
logThis.debug(msg='This message is from logger') # Logs!
add a comment |
A couple of points to know (Read these logging docs for details)
- A parent's / ancestor's log level takes precedence while evaluating the effective log level
- A root logger, for example that created with getLogger, has WARNING as it default log level
You have set the log level of the handler (logHandler) but not the root (logger). At this point, no handler can have a log level less than the root's, ie, WARNING
logHandler.setLevel(level)
logger.addHandler(logHandler)
logThis.debug(msg='This message is from logger') # Does not log
logThis.warn(msg='This message is from logger') # Logs
So, set the root level to something reasonable and you should be good to go
logHandler.setLevel('WARNING') # or NOTSET
logThis.debug(msg='This message is from logger') # Logs!
add a comment |
A couple of points to know (Read these logging docs for details)
- A parent's / ancestor's log level takes precedence while evaluating the effective log level
- A root logger, for example that created with getLogger, has WARNING as it default log level
You have set the log level of the handler (logHandler) but not the root (logger). At this point, no handler can have a log level less than the root's, ie, WARNING
logHandler.setLevel(level)
logger.addHandler(logHandler)
logThis.debug(msg='This message is from logger') # Does not log
logThis.warn(msg='This message is from logger') # Logs
So, set the root level to something reasonable and you should be good to go
logHandler.setLevel('WARNING') # or NOTSET
logThis.debug(msg='This message is from logger') # Logs!
A couple of points to know (Read these logging docs for details)
- A parent's / ancestor's log level takes precedence while evaluating the effective log level
- A root logger, for example that created with getLogger, has WARNING as it default log level
You have set the log level of the handler (logHandler) but not the root (logger). At this point, no handler can have a log level less than the root's, ie, WARNING
logHandler.setLevel(level)
logger.addHandler(logHandler)
logThis.debug(msg='This message is from logger') # Does not log
logThis.warn(msg='This message is from logger') # Logs
So, set the root level to something reasonable and you should be good to go
logHandler.setLevel('WARNING') # or NOTSET
logThis.debug(msg='This message is from logger') # Logs!
answered Nov 26 '18 at 7:30
rhino2rhondarhino2rhonda
404514
404514
add a comment |
add a comment |
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.
The docs state:
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger).
So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler.
Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...
... until either an ancestor with a level other than NOTSET is found, or
the root is reached.
[...]
If the root is reached, and it has a level of NOTSET, then all
messages will be processed. Otherwise, the root’s level will be used
as the effective level.
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default.
You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.
add a comment |
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.
The docs state:
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger).
So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler.
Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...
... until either an ancestor with a level other than NOTSET is found, or
the root is reached.
[...]
If the root is reached, and it has a level of NOTSET, then all
messages will be processed. Otherwise, the root’s level will be used
as the effective level.
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default.
You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.
add a comment |
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.
The docs state:
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger).
So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler.
Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...
... until either an ancestor with a level other than NOTSET is found, or
the root is reached.
[...]
If the root is reached, and it has a level of NOTSET, then all
messages will be processed. Otherwise, the root’s level will be used
as the effective level.
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default.
You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.
You are missing the fact that a) every logger's ultimate ancestor is the root logger (which has level WARNING by default) and b) that both, loggers and handlers have levels.
The docs state:
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger).
So, you create a logger and a StreamHandler with their default level NOTSET. Your logger is an implicit descendant of the root logger. You set the handler to level DEBUG, but not the logger using that handler.
Since the level on your logger still is NOTSET, when a log event occurs, its chain of ancestors is traversed ...
... until either an ancestor with a level other than NOTSET is found, or
the root is reached.
[...]
If the root is reached, and it has a level of NOTSET, then all
messages will be processed. Otherwise, the root’s level will be used
as the effective level.
Which means, you immediately end up at the root logger to determine the effective log level; it is set to WARNING as per the root logger's default.
You can check this with the parent and level properties and the getEffectiveLevel method on the logger object:
logThis = get_logger()
print(logThis.parent) # <RootLogger root (WARNING)>
print(logThis.level) # 0 (= NOTSET)
print(logThis.getEffectiveLevel()) # 30 (= WARNING) from root logger
To have your logger handle the messages on and above the desired level itself, simply set it on the logger via logger.setLevel(level) in your get_logger function.
edited Nov 28 '18 at 6:37
answered Nov 26 '18 at 8:24
shmeeshmee
1,5611711
1,5611711
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%2f53475104%2fpython-how-to-create-and-use-a-custom-logger-in-python-use-logging-module%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
First, you are not using
logThisvariable for logging which is returned by your get_logger function, second DO NOT use type as a name of a variable astypeis a keyword in Python.– Ankit Jaiswal
Nov 26 '18 at 5:24
The default root level logger is set to
WARNINGlevel.– Ankit Jaiswal
Nov 26 '18 at 5:30
I am of the view that if I am creating a custom logger then I should be able to see the messages from that logger. Irrespective of what settings root logger has. Am I right or missing something?
– exan
Nov 26 '18 at 6:33
you have edited your question, are you still not able to get the desired output? In your previous code, you did create your custom logger but you were not using that. Instead you were using the default logger settings from root logger.
– Ankit Jaiswal
Nov 26 '18 at 7:43
@AnkitJaiswal: Thanks for the pointing out the typos. I edited the post to match my code, however problem is somewhere else and not because of the typos.
– exan
Nov 26 '18 at 23:49