1

I have this logger class I created and it works perfectly for a project I have but when I simply copy and paste the structure to another project it doesn't work. The logs I try to write do not appear in the file specified nor in the console.

This is the code:

import logging


class Logger:
    def __init__(self, path=None, name=None):
        format_string = '%(asctime)s : T%(relativeCreated)05ds : %(levelname)-8s - %(name)s : %(message)s'
        format_date = '%Y-%m-%dT%H:%M:%S'

        # BASIC CONFIG
        if path is not None:
            logging.basicConfig(filename=path, filemode='a', format=format_string, datefmt=format_date)

        # START LOGGER
        logger = logging.getLogger(name)

        if path is None:
            # DEFINE FORMAT 
            handler = logging.StreamHandler()
            formatter = logging.Formatter(fmt=format_string, datefmt=format_date)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

        # LEVEL SET
        logger.setLevel(logging.DEBUG)

        logger.info('TEST')

        self.logger = logging.getLogger(__name__)
        self.logger.info(f'START NEW EXECUTION\n\n{"=" * 36}\n')

The line self.logger.info(f'START NEW EXECUTION\n\n{"=" * 36}\n') doesn't print anything to the file set by the variable path. And this only happens when I add a name to the logger. I added this name variable as a suggestion I found in order to avoid writing logs of Python Modules.

I feel like I am doing something very simple (I have just started using the Logging Module) that is causing this problem but I can't see it since this exact structure works fine in another project.

EDIT0: My final goal is to have a Logger Class I can use in any project just by copying the file and using it the same way, if anyone has something like this and wouldn't mind sharing, then it would be enough for me.

1 Answer 1

3

My final goal is to have a Logger Class I can use in any project just by copying the file and using it the same way, if anyone has something like this and wouldn't mind sharing, then it would be enough for me.

I would recommend creating something you can import rather than copy pasting the code, this way if you want to make a change you only have to update it in one place. But since you are open to using existing tools, I would recommend either the default logger or my personal favorite, loguru.

Example from loguru

from loguru import logger

logger.debug("That's it, beautiful and simple logging!")
Sign up to request clarification or add additional context in comments.

6 Comments

It would still be necessary to add some code to this loguru to configure everything to be the way I want it to be I guess (all the formats for dates, strings, things like that). Is it anyhow easier to do it using this module or not?
loguru is pretty easy to customize, you can use logger.remove() to delete the default sink then add custom ones logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>"). You can find the full documentation here.
how to use the same log for different python files?
You can create a new sink for logs to be sent to, for example logger.add("file.log").
No, you only need to add this line once per project then other files can import the logger from logger import logger and it will automatically have the same sinks.
|

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.