Logging Config in Python

2021-04-28
1 min read

A simple python note about logging config

import os
import time
import logging

save_dir = 'onefolder/logs/anotherfolder'
sub_dirs = save_dir.split('/')
sub_dir = '.'
for i in range(len(sub_dirs)):
    sub_dir = os.path.join(sub_dir, sub_dirs[i])
    if not os.path.isdir(sub_dir):
        os.mkdir(sub_dir)

logging.basicConfig(
    format="%(asctime)s %(levelname)-8s %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S",
    filename=os.path.join(save_dir, 'recommender_conceptnet-' +
                          time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime()) + '.log')
)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s")
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)
logging.info("Saving logs in: {}".format(save_dir))

logging.info("Something you want to save in the logs...")
Avatar
Hanfang Lyu | Pearl Slowly Updating...

See Also