Table of Contents
Use logging.basicConfig()
to log to stdout
To log to stdout
in Python:
- Specify the format in which we want to have all logs.
- Use the helper function
.basicConfig()
to perform basic logging for the logging system. - Use
.getLogger()
to create a logger with the specified name (if it is); otherwise, it will create aroot
logger. - Use
.error()
to log theERROR
level message on the console.
1 2 3 4 5 6 7 8 |
import logging log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" logging.basicConfig(format = log_format, level = logging.ERROR) logger = logging.getLogger() logger.error("Logging First Error") |
The above code block will display the following output on the console.
1 2 3 |
2022-11-28 17:00:46,865 - root - ERROR - Logging First Error |
We used a helper function known as .basicConfig()
to perform basic logging by creating the StreamHandler
with the specified Formatter
and adding it to a root
logger.
You might have a few questions by reading the above sentence, for instance, what is StreamHandler
, how they are created, what is root
, and how it is being added to the root
logger. Let’s address these questions before diving into more details of the .basicConfig()
function.
The StreamHandler
is a handler used for logging to the console. We created a root
logger in our application by calling logging.getLogger()
, which creates a root
logger by default.
We can also name the logger of our choice by passing a custom name to this function, for example, logging.getLogger("MyLogger")
. The logger.error()
invokes the .basicConfig()
; this is how it is added to the root
logger.
Now, the point is how we are creating StreamHandler
. The handlers
is one of the parameters that we can set while using the .basicConfig()
method. The handler
parameter is iterable and used to have the handlers, for instance, logging.FilHandler()
and logging.StreamHandler()
.
If we don’t set the handler
parameter, it acts as StreamHandler
by default. This is how StreamHandler
is created. You can learn more about it here. Now, let’s return to the .basicConfig()
method and explore more about it below.
The .basicConfig()
does nothing if the root
logger has configured handlers already unless force
is set to True
. Here, configured handlers mean that the .basicConfig()
method has a handlers
parameter set something as follows:
1 2 3 4 5 6 7 8 9 |
stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setFormatter(logging.Formatter("%(message)s")) logging.basicConfig(level=logging.ERROR, handlers=[ logging.FileHandler("file.log"), stream_handler ]) |
In our code example, we passed two parameters to .basicConfig()
function that are briefly explained below:
-
format
– It is used to specify a particular format to display logs. If it is not given, the.basicConfig()
will log in default format aslogger level: logger name: log message
. For instance,ERROR: root: Logging First Error
. -
level
– It denotes the logger’s level. We have six levels in thelogging
module:CRITICAL
,ERROR
,WARNING
,INFO
,DEBUG
, andNOTSET
. If nolevel
parameter is given, it will set the logging level toNOTSET
in thelogging
module.
Remember that the info()
, debug()
, error()
, warning()
, and critical()
functions will automatically invoke .basicConfig()
if any handler is not defined for a root
logger.
Make sure to distinguish these logging functions from logging levels. The logging levels are not the same as logging functions but are the constants with some associated integer number.
For instance, logging.ERROR = 10
. Similarly, CRITICAL
, WARNING
, INFO
, DEBUG
, and NOTSET
also have some associated integers.
Next, we called the logging.getLogger()
method to create a root
logger. Finally, we used the logging.error()
method with a logging level ERROR
to log messages on a root
logger.
Use logging.StreamHandler()
to log to stdout
To log to stdout
:
- Use
.getLogger()
to create a logger namedMyFirstLogger
. Note that thename
parameter is optional. - Use
.StreamHandler()
to log to the console. - Use
.Formatter()
to get aFormatter
class’ instance initialized with the format string; this format string will be used while displaying log messages on the console or file. - Next, use
.setFormatter()
to set the formatter (created in the previous step) onStreamHandler
. - Use
.addHandler()
to add thestream_handler
to our logger. - Use
.error()
to log theERROR
level message on the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import logging import sys log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" logger = logging.getLogger("MyFirstLogger") stream_handler = logging.StreamHandler(stream = sys.stdout) formatter = logging.Formatter(log_format) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.error("Logging First Error") |
This code will print the log on the console as follows.
1 2 3 |
2022-11-29 04:30:10,959 - MyFirstLogger - ERROR - Logging First Error |
We used .getLogger()
to create a logger with a name of our choice. We can also call this method without passing the name
parameter. In that case, this function would create a root
logger.
Next, we used a .StreamHandler()
handler by setting a stream
parameter to sys.stdout
to log to the console. Here, we can change the value of the stream
parameter based on where to send logging output, for instance, sys.stdout
, sys.stderr
, file-like object or any object supporting flush()
and write()
.
Note that we have different handlers in the logging
module that we can choose from based on project requirements, such as SocketHandler
, RotatingFileHandle
, DatagramHandler
, NullHandler
, and FileHandler
.
We used StreamHandler()
to log to the console, but you can also use FileHandler()
to log to the file. Check the Python documentation for more details for each of the logging handlers.
Then, we used the .Formatter()
function by specifying a log_format
, which contained a string format to format logs. The .Formatters()
are accountable for transforming internal log records into human-readable string formats.
Following the previous step, we used .setFormatter()
to set the formatter on the SteamHandler
, which means the logging
module will use this formatter
to format all the messages before displaying them on the console.
Next, we used .addHandler()
to add a stream handler to the logger and finally used .error()
to log the ERROR
level message on the console.