0

I've a generic file log.py in which i've imported python logging and used all functions in it.

now i need to format log such that

(current_script_name) [levelname] message

log.py

import logging
import inspect
import sys

class log(object):
    #file_name = sys.argv[0] #this will give b.py instead of a.py
    file_name = str(inspect.getfile(inspect.currentframe())).split("/")[-1]
    logging.basicConfig(level=logging.INFO, format="("+file_name+") [%(levelname)s] %(message)s")
    def __init__(self):
        pass
    def info(msg):
        logging.info(msg)
    def error(msg):
        logging.error(msg)
    def warning(msg):
        logging.warning(msg)
    def debug(msg):
        logging.debug(msg)

Now, i've another file called a.py where i have imported above file and used like

import log
def some():
    log.info("Hello this is information")

This will give an output below when i call some() in b.py

(log.py) [INFO] Hello this is information

but i expect below output because log.info() code is used in a.py

(a.py) [INFO] Hello this is information

Note: I shouldn't pass any argument for log.info(msg) line in a.py

1 Answers1

0

One solution would be to pass the file name of the executing script to the logger.

Inside a.py:

log.info("Hello this is information", executing_script=__file__)

(For more information about using the file variable: https://note.nkmk.me/en/python-script-file-path/)

You would have to update all the function definitions in your log class if you do it this way though. Alternatively, you could include the executing script file name in the log class initializer:

class log(object):
  def __init__(self, executing_script):
    self.file_name = executing_script
  # ...

This way you can just reference self.file_name in your logging functions instead of having to pass a value to each one.

Rekamanon
  • 217
  • 2
  • 10
  • Hi @Rekamanon, this could be helpful but not much because i need to avoid passing arguments – Arunkumar G Nov 01 '19 at 12:13
  • Maybe this question is relevant to your problem: https://stackoverflow.com/questions/24114712/how-to-get-the-caller-script-name – Rekamanon Nov 01 '19 at 12:15