Home [Python] Custom Logger
Post
Cancel

[Python] Custom Logger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import logging

def init_logger(name):
    logger=logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    #Creating Formatters    
    formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
    #Creating Handlers
    # handler = logging.FileHandler('./logs/test.log')
    handler = logging.StreamHandler()
    #Adding Formatters to Handlers
    handler.setFormatter(formatter)
    handler.setLevel(logging.DEBUG)
    #Adding Handlers to logger
    logger.addHandler(handler)
    return logger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import logging

from logging.handlers import RotatingFileHandler
import colorlog

def init_logger(name, debug_mode=False):
    color_log_format = (
        '%(asctime)s '
        '%(log_color)s'
        '%(levelname)s '
        '%(reset)s'
        '%(message)s '
        '- %(processName)s %(threadName)s '
        '- %(filename)s:%(funcName)s:%(lineno)d'
        '%(reset)s'
    )
    log_format = (
        '%(asctime)s '
        '%(levelname)s - '
        '%(message)s '
        '%(filename)s:%(funcName)s;%(lineno)d'
    )
    colorlog.basicConfig(format=color_log_format)
    logger = logging.getLogger(name)

    if debug_mode:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    # Output full log
    logging_dir = 'logs'
    if not os.path.exists(logging_dir):
        os.makedirs(logging_dir)

    handler = RotatingFileHandler(f'{logging_dir}/%s.log' % name,
                             mode='a',
                             maxBytes=5*1024*1024,
                             backupCount=3)
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    # Output warning log
    handler = RotatingFileHandler(f'{logging_dir}/%s.warn.log' % name,
                             mode='a',
                             maxBytes=5*1024*1024,
                             backupCount=3)
    handler.setLevel(logging.WARNING)
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    # Output error log
    handler = RotatingFileHandler(f'{logging_dir}/%s.err.log' % name,
                             mode='a',
                             maxBytes=5*1024*1024,
                             backupCount=3)
    handler.setLevel(logging.ERROR)
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    return logger
This post is licensed under CC BY 4.0 by the author.

[MySQL] Workbench UI Docker

[Python] Pandas DataFrame을 MySQL로 INSERT