How to create a simple logger in Python, first part

The Python computer programming language offers a builtin module which can be utilized to log applications. Being a junior developer, lately I have started to realize the importance of logging.

Before one can properly make use of the Python’s builtin logging module, they need to learn the basics. Through this tutorial, the reader is going to learn how to create a simple logger with the help of the Python’s builtin module, so they can build some basic foundation which can be useful later in their serious projects.

First, make sure to launch a new Python interactive shell in your own operating system so you can practice the code being shared through this article. Once you have managed to do that, it is time to get your hands dirty.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Import the Python’s builtin logging module

For one to make use of a module in the Python computer programming language, they need to import it first.

Let’s import the logging module through the following piece of Python code.

import logging

Now that we have included the Python’s builtin logging module in our interactive session, we can easily make use of the functionalities included inside it. The first function which we need to make use of is the one which is shown below.

logging.basicConfig

The above builtin function, part of the Python’s builtin logging module, can be used to configure a logger object.

Based on my personal experience with the logging.basicConfig function, it takes keyword arguments such as the filename in which the logs will be stored, the level of logging and also the mode of writing the logs.

We will see everything through a practical example.

Let’s create our simple logger as a custom module

Create a new Python script with your favorite text editor like shown below.

hack_logging.py

Once you have managed to do that, write the first line of Python code like shown below.

import logging

We need to import the Python’s builtin logging module so we can make use of its functionalities in our custom module.

Once we have imported the Python’s builtin logging module like shown above, we need to define a basic logger through the logging.basicConfig function.

We are going to define a main function first.

import logging


def main():
    pass

The function which we have defined in the above module, will serve as the main entry point of our simple application. We are going to setup our basic logger inside this function.

So let’s do it.

import logging


def main():
    logging.basicConfig(level=logging.INFO, filename='storelogs.log')    

Now we have managed to setup our custom logger. There are two keyword arguments passed in the above main function; the level of logging and the filename.

The level of logging specifies what kind of logging the application is going to handle. Based on my personal experience with the Python’s builtin logging module there are five levels of logging.

Each one of them is being shown below.

logging.INFO
logging.DEBUG
logging.ERROR
logging.WARNING
logging.CRITICAL

For now, we have setup the level of logging to logging.INFO. This level of logging fits our purpose as this time we are going to log all informational messages inside our storelogs.log file.

The coder is free to specify their filename; I recommend that your define it as shown in this article.

Now let’s do some logging…

There are specific functions included in the Python’s builtin logging module which can help us to log in our application.

The ones we need are being explained below.

logging.info, logs informational messages
logging.error, logs errors in your applications such as entire tracebacks

Back to the code. Make sure that the local Python module which you have already created looks like the one shown below.

import logging

def main():
    logging.basicConfig(level=logging.INFO, filename='storelogs.log')
    logging.info('This is some informational message')
    logging.error('This is an error log')    

Our custom logger is not finished yet. To get the main entry point of the application executed automatically, we need to add the following Python line at the end of the module.

import logging

def main():
    logging.basicConfig(level=logging.INFO, filename='storelogs.log')
    logging.info('This is some informational message')
    logging.error('This is an error log') 


if __name__ == '__main__':
    main()   

Based on my personal experience, the above if conditional returns always True, so the main() function will get executed every time we call our module from the terminal console.

You can also test it yourself in an interactive Python shell.

if __name__ == '__main__':
    print("True")

Once the above piece of Python code got executed in my interactive session, I got the following output.

True

Now that our custom module looks fine, let’s give it a try by executing it through the terminal console.

python hack_logging.py

If you have coded the custom logger the same as me, after executing it through the above command, the logs will be stored inside the file storelogs.log.

The final result is being shown below.

INFO:root:This is some informational message
ERROR:root:This is an error log

As you can see from the above logs, which are being stored inside the storelogs.log file, each one of the logs has its level of logging in uppercase letters.

Final thoughts

Logging is a very important aspect of programming, especially if you want to advance your skills and become a professional developer. Through this article, we managed to create a simple custom logger which for now is fine for the beginner coder.

In the next part we are going to extend our custom logger so we can build a more advanced working one.

Reference: https://www.blog.pythonlibrary.org/2012/08/02/python-101-an-intro-to-logging/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *

*