Create an independent Python logger and save reports into file


This is just a trivial task which we want to run a python files and logging all actions.
We want to save all the reports into file. Then, you can just doing this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
import os
import logging

logger = logging.getLogger(‘test’)
log_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ‘test.log’))
log_file = logging.FileHandler(log_path)
formatter = logging.Formatter(‘%(asctime)s %(levelname)s %(message)s’)
log_file.setFormatter(formatter)

logger.addHandler(log_file)
logger.setLevel(logging.INFO)

logger.error("Ouch! it’s hurt!")

Explanation:

1.getLogger(‘test’)
We need to create logger name. This can be whatever name.

2. log_path
This is where the log stored.

3. log_file
This is we tell logging FileHandler to get where the log file will be created.

4. formatter
This is contain format style of logs

5. logger.addHandler & logger.setLevel
This is we want to attach handler and level into logger that we want to use to log anything.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.