5

I am new to Python and trying to implement logger in my code. I have created a python file: setup_logger.py

import logging

CLASS_NAME = ''

# Create and configure logger
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(filename='/Users/bobby/Desktop/lumberjack.log', level=logging.DEBUG, format=LOG_FORMAT)
logger = logging.getLogger()

I am using this logger configuration in another python file: GetLogger.py as below

from LoggerLevels.setup_logger import logger

if __name__ == '__main__':
    logger.error('This is a basic log error message')
    logger.info('This is a warning message')

The log is being printed in the file as:

2020-06-17 14:54:47,161 - root - ERROR - This is a basic log error message
2020-06-17 14:54:47,161 - root - INFO - This is a warning message

But I see the class name is printed as root. I understand that it is coming due to the setting in setup_logger.py file. Is there anyway I can send the current class name that is logging messages into my file ? For ex: I am using the logger object from GetLogger.py file. Is there anyway I can log the message as

2020-06-17 14:54:47,161 - GetLogger - ERROR - This is a basic log error message
2020-06-17 14:54:47,161 - GetLogger - INFO - This is a warning message

Could anyone let me know how can I achieve that ?

1

2 Answers 2

5

Use:

LOG_FORMAT = '%(asctime)s - %(module)s - %(levelname)s - %(message)s'

If that doesn't work for you, you can try %(filename)s or create a custom class with setLoggerClass method.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a advice for you to take it as a reference.

logger_format = '%(asctime)s [%(className)s] %(funcName)s | %(message)s (%(name)s)'
extra_dict = {'className': 'NameOfClass'}
logger = logging.getLogger('logger_name')

def callLogger():
    logger.debug('log message', extra=extra_dict)

callLogger()

And result would be like:

2021-02-21 17:08:34,066 [NameOfClass] callLogger | log message (logger_name)

When we use the same logger in different class, this way is also work.

If you use different logger in each class, you have easier way like:

# put the (%(name)s) to position of name of class
logger_format = '%(asctime)s [%(name)s] %(funcName)s | %(message)s'

# name the logger name as class name
logger = logging.getLogger('NameOfClass')

def callLogger():
    logger.debug('log message')

callLogger()

And result would be like:

2021-02-21 17:08:34,066 [NameOfClass] callLogger | log message

Refer to Python official document

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.