1

I have a logger.py file which initialises logging.

import logging

logger = logging.getLogger(__name__)

def logger_init():
    import os
    import inspect
    global logger  

    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    logger.addHandler(ch)

    fh = logging.FileHandler(os.getcwd() + os.path.basename(__file__) + ".log")

    fh.setLevel(level=logging.DEBUG)
    logger.addHandler(fh)

    return None

logger_init()

I have another script caller.py that calls the logger.

from logger import *
logger.info("test log")

What happens is a log file called logger.log will be created containing the logged messages.

What I want is the name of this log file to be named after the caller script filename. So, in this case, the created log file should have the name caller.log instead.

I am using python 3.7

user3848207
  • 3,737
  • 17
  • 59
  • 104

2 Answers2

3

It is immensely helpful to consolidate logging to one location. I learned this the hard way. It is easier to debug when events are sorted by time and it is thread-safe to log to the same file. There are solutions for multiprocessing logging.

The log format can, then, contain the module name, function name and even line number from where the log call was made. This is invaluable. You can find a list of attributes you can include automatically in a log message here.

Example format:

format='[%(asctime)s] [%(module)s.%(funcName)s] [%(levelname)s] %(message)s

Example log message

[2019-04-03 12:29:48,351] [caller.work_func] [INFO] Completed task 1.
edd
  • 1,307
  • 10
  • 10
  • Thank you. This is a superior solution compared to the ones provided in https://stackoverflow.com/questions/1095543/get-name-of-calling-functions-module-in-python – user3848207 Apr 29 '20 at 17:14
-1

You can get the filename of the main script from the first item in sys.argv, but if you want to get the caller module not the main script, check the answers on this question.

M. Elghamry
  • 322
  • 2
  • 8