Welcome, guest | Sign In | My Account | Store | Cart

Every Python logging manual have this code:

logging.basicConfig(level=logging.DEBUG, filename='debug.log',
                    format='%(asctime)s %(levelname)s: %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

This is a simple function which call it for you. All you need is remember one function name; useful on little scripts.

Python, 36 lines
 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
# -*- coding: Windows-1251 -*-
import datetime
import logging
import os
import sys

def quick_start_log(log_fn=None, mode=None, level=logging.DEBUG, \
                    format='%(asctime)s|%(name)s|%(levelname)s| %(message)s'):
    '''
    simplest basicConfig wrapper, open log file and return default log handler
    '''

    if log_fn is None:
        now = datetime.datetime.now()
        ts = now.strftime('%Y-%m-%d_%H%M%S')
        log_fn = '%s.%s.log' % (sys.argv[0], ts)

    if mode is None:
        mode = 'w'

    logging.basicConfig(level=level,
                        format=format,
                        filename=log_fn,
                        filemode=mode)

    logger = logging.getLogger('main')
    if mode.lower() == 'a':
        logger.info('---=== START ===---')

    return logger


if __name__ == '__main__':
    log = quick_start_log()
    log.info('message')
    log.fatal('exit')