Code for Creating a Logger When Making Python Command Line Tools

Python
2022-10-09 02:16 (3 years ago)
Code for Creating a Logger When Making Python Command Line Tools

Here is a memo on the code for creating a logger when making a simple daemon application in Python.

import logging

_logger = logging.getLogger('my-application-name')


def _my_procedure(...):
    ...
    _logger.debug(...)
    ...
    


def setup_logger():
    _logger.setLevel(logging.DEBUG)
    _handler = logging.StreamHandler()
    _handler.setFormatter(logging.Formatter(
        '%(asctime)s %(thread)d %(name)s %(levelname)s %(message)s'
    ))
    # When formatting heavily
    # _handler.setFormatter(logging.Formatter(
    #     '%(name)s (%(process)d,%(thread)d) '
    #     '%(levelname)s %(asctime)s '
    #     '[%(module)s.%(funcName)s:%(lineno)d] '
    #     ' %(message)s'
    # ))
    _logger.addHandler(_handler)


if __name__ == '__main__':
    setup_logger()
    ...

This code sets up a basic logger for a Python application. The logger is configured to output messages to the console with a specific format and can be further customized if needed.

Please rate this article
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive