poobear
poobear

Reputation: 73

How to redirect python logger info to a log file in python

I want to write all of python logger messages to a log file. I have this code, but the code displays messages on the console and just creates the log file, but writes nothing to it.

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
    handlers=handlers
)
logger = logging.getLogger("somename")

What am i doing wrong here

Upvotes: 0

Views: 423

Answers (1)

Rahil Hastu
Rahil Hastu

Reputation: 558

do, this instead:

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
    filename='tmp.log'
)
logging.debug("somename")

If filename parameter is provided in basicConfig it means the file is opened in this mode. The default is a, which means append.

Upvotes: 1

Related Questions