Code for Creating a Logger When Making Python Command Line Tools

Python
2022-10-09 11:16 (2 years ago) ytyng

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.

Currently unrated
著者は、アプリケーション開発会社 Cyberneura を運営しています。
開発相談をお待ちしています。

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011