Python Logging Basic Configurations
To configure the python logging module, to set the log level, log format, etc., we can use the basicConfig(**kwargs)
method where **kwargs
in the function definition means this function takes variable length arguments, which should be passed in the key-value form.
Some commonly used parameters in the basicConfig()
function is given below:
-
level
: With the help of this parameter the root logger will be set to the specified severity level, like DEBUG, INFO, ERROR, etc.
-
filename
: This parameter is mainly used to specify the file name if we want to store the logs in a file.
-
filemode
: If the filename
is given, the file is opened in this mode. The default mode is a
, which means append.
-
format
: This is used to specify the format of the log message. For example, if you want to add timestamp with the logs, or the name of the python script or maybe the function or class name in the logs, then we can specify the appropriate format for that.
In the basicConfig()
function we can either provide the level parameter with an appropriate value, filename and filecode for printing logs in file, and the format parameter to specify the logs, or you can specify all the parameters together, that is the beauty of **kwargs
, which means the number of arguments that can be supplied to a function is not fixed.
Let's take an Example
Let us take a look at the example for the clear understanding of this method:
import logging
logging.basicConfig(level=logging.INFO)
logging.info('This is an info message.This will get logged.')
INFO:root: This is an info message. This will get logged.
All events at or above INFO
level will now get logged.
Points to remember:
-
It is important to note here that calling basicConfig()
to configure the root logger works in the case only if the root logger has not been configured before. Basically, this function can only be called once.
-
Also debug()
, info()
, warning()
, error()
, and critical()
, all these functions internally call basicConfig()
method without any arguments automatically if it has not been called before.
-
This means that after the first time one of the above-given functions is called, you can no longer configure the root logger because they would have called the basicConfig()
function internally.
Thus the default setting in basicConfig()
is to set the logger to write to the console in the following format:
ERROR:root: This is an error message
With log level, logger name and then the log message.
Store Logs in File
We can use the basicConfig()
method to store logs in a file. How we can do so, we will learn in the next tutorial where we will cover how to store Python code logs in a file.
Set Format of Logs
We can configure the logging module to print logs in a any format we want. There are some standard formats which are universally used, and we can configure the python logger to print logs in those formats.
There are some basic components of logs that are already a part of the LogRecord and we can easily add them or remove them from the output format.
Let's take a few examples to understand this.
Add process ID to logs with loglevel and message
If you want to include the process ID for the running python script along with the log level and message then the code snippet for the same is given below:
import logging
logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This message is a warning')
1396-WARNING-This message is a warning
In the code above, in the basicConfig()
method, we have set the format
parameter with the format string as value in which we have specified, what components we want in our log, along with specifying its datatype, like d
with process to print the integer process Id, then s
for loglevel which is string value, and same for the message
Also, in the code above, we can set the format with the LogRecord
attributes set in any order.
Add Timestamp to logs with log message
You can also add date and time info(timestamp) to your logs along with the log message. The code snippet for the same is given below:
import logging
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('This message is to indicate that Admin has just logged in')
2020-06-19 11:43:59,887 - This message is to indicate that Admin has just logged in
In the above code %(asctime)s
adds the time of the creation of the LogRecord
. Also, we have configured the log level too with code level=logging.INFO
.
Use the datefmt
attribute
You can also change the format using the datefmt
attribute, which uses the same formatting language as the formatting functions in the datetime module, such as time.strftime()
:
import logging
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
logging.warning('The Admin just logged out')
19-Jun-20 11:50:28 - The Admin just logged out
As you can see the log printed as the output of the above code has a date format DD-MMM-YY along with time.
So, using the basicConfig(**kwargs)
method, we can configure the logs format as we want, like adding timestamp to logs, adding process id to logs, printing log level along with logs and log messages.