0

this is the code i've made so far:

    import logging, os , json, inspect, sys
from logging import handlers

class StructuredMessage(object):
    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def __str__(self):
        return '%s' % (json.dumps(self.kwargs))

    def setup(self, file):        
        if(os.getenv('LOG_TO_FILE') == 'True'):
            logging.basicConfig(filename='logs/'+file, format='%(levelname)s %(asctime)s  %(message)s', filemode='a')             
        else:
            logging.basicConfig(filename='logs/'+file, format='%(levelname)s %(asctime)s %(message)s', filemode='a')

logger = logging.getLogger()

def info(msg):
    fun = StructuredMessage()
    fun.setup('info.log')
    logger.setLevel('INFO')
    frame = ''.join(str(inspect.currentframe().f_back.f_code.co_filename))
    lNo = ''.join(str(inspect.currentframe().f_back.f_code.co_firstlineno))
    logging.info(StructuredMessage(msg=msg, file=frame+':'+lNo))

def error(msg):
    fun = StructuredMessage()
    fun.setup('exception.log')
    logger.setLevel('ERROR')
    frame = ''.join(str(inspect.currentframe().f_back.f_code.co_filename))
    lNo = ''.join(str(inspect.currentframe().f_back.f_code.co_firstlineno))    
    logging.error(StructuredMessage(msg=msg, file=frame+':'+lNo))

What i'm trying to achieve is to obtain a module which when i call info function (for example) writes the message in the specified file in basicConfig.

The wrong is that when i call the error function it writes the error in the info.log file instead of the exception.log file, and info.log file contains both the messages.

The goal is to get to separate functions, info and error , that each one of them writes exclusively on the specified file.

What i'm doing wrong?

xCloudx8
  • 601
  • 8
  • 21
  • 1
    You may want to spend more time reading the `logging` package's doc - it's not the funniest way to spend time for sure, but it's __really__ worth the effort, as proper logging is a very valuable skill that will help you for years. To make a long story short: you don't need any of this mess (sorry), just proper logging configuration and usage. NB: Note that your loggers should only ever be configured once per process. – bruno desthuilliers Apr 15 '20 at 11:53
  • Thank you @brunodesthuilliers , i'm trying hard without success, but as you said i will try to follow your suggestion – xCloudx8 Apr 15 '20 at 12:02
  • The first and most important thing to understand re the logging package is the division between library code and application code - your library code should only _use_ logging (instanciate a logger and call it where required), and the app entry point should be responsible for configuring the loggers according to the app's own needs. – bruno desthuilliers Apr 15 '20 at 12:21
  • The second point is to understand that loggers form a hierarchy based on the logger's "qualified name" (iow in dots in the name), so if you have one logger created as `logging.getLogger("parent") and another as `logging.getLogger("parent.child"), the second will indeed be a child of the first and - if not explicitely configured to do otherwise - will delegate to it's parent. This allow for very fined grained configuration when needed. Canonically, one will use the module's name (thru the `__name__` magic variable) to name a module-level logger. wrt/ config, `DictConfig` is by far the easiest. – bruno desthuilliers Apr 15 '20 at 12:41
  • And finally, don't forget that you can configure loggers to NOT delegate to their parents too, and that you can set logging level not only on a logger itself but also on each of it's handlers, so you can have multiple handlers for different levels for a same handler. – bruno desthuilliers Apr 15 '20 at 12:43

0 Answers0