I want to write a Python class which uses Python logging. This Python class will be responsible for the creating a file with a given name in init function.
I want
This is better handled using dictConfig. You can then specify logging to two seperate files. I utilize the second_logger only when an API post is made so that I can log external data to the second log.
import os, logging
from logging.config import dictConfig
FORMAT = "%(asctime)s {app} [%(thread)d] %(levelname)-5s %(name)s - %(message)s. [file=%(filename)s:%(lineno)d]"
DATE_FORMAT = None
def setup_logging(name, level="INFO", fmt=FORMAT):
formatted = fmt.format(app=name)
log_dir = r'C:/log_directory'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging_config = {
"version": 1,
'disable_existing_loggers': False,
"formatters": {
'standard': {
'format': formatted
}
},
"handlers": {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
'level': level,
'stream': 'ext://sys.stdout'
},
'file': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': 'midnight',
'utc': True,
'backupCount': 5,
'level': level,
'filename': '{}/app_manager.log'.format(log_dir),
'formatter': 'standard',
},
'file2': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': 'midnight',
'utc': True,
'backupCount': 5,
'level': level,
'filename': '{}/unified_log.log'.format(log_dir),
'formatter': 'standard',
}
},
"loggers": {
"": {
'handlers': ['default', 'file'],
'level': level
},
"second_log": {
'handlers': ['default', 'file2'],
'level': level
}
}
}
dictConfig(logging_config)
log.setup_logging(name="log-name", level=LEVEL
logger = logging.getLogger(__name__)
second_logger = logging.getLogger('second_log')
second_logger.propagate = False