Basic information for logging

less than 1 minute read

Logging using formatting

import logging
from datetime import datetime

logger = logging.getLogger(__name__)
formatter = logging.Formatter('[%(asctime)s][%(levelname)-8s|%(filename)s:%(lineno)s] >> %(message)s')

# stdout
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# fileout
#fileHandler = logging.FileHandler('./test.log')
fileHandler = logging.FileHandler('{:test.%Y%m%d}.log'.format(datetime.now()))
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)

logger.setLevel(level=logging.DEBUG)

logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

Result

[2021-02-01 08:59:10,557][DEBUG   |<stdin>:1] >> debug
[2021-02-01 08:59:10,578][INFO    |<stdin>:1] >> info
[2021-02-01 08:59:10,591][WARNING |<stdin>:1] >> warning
[2021-02-01 08:59:10,602][ERROR   |<stdin>:1] >> error
[2021-02-01 08:59:11,099][CRITICAL|<stdin>:1] >> critical

Using environment

import os
os.environ['TEST_HOME'] = os.getenv('HOME')
home = os.getenv('TEST_HOME')
print home
home = os.environ.get('TEST_HOME')
print home

Tags:

Categories:

Updated:

Leave a comment