Django Logging custom messages!

Hi guys,

Problem: I need to log some actions to a file when they are performed, but only this specific messages and nothing else.

I create the settings to log to a file and it worked, but write my messages and a bunch of trash.

Settings.py

LOGGING = {
    # Define the logging version
    'version': 1,
    # Enable the existing loggers
    'disable_existing_loggers': False,

    # Define the handlers
    'handlers': {
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'djangoapp.log',
        },
        'console': {
            'class': 'logging.StreamHandler',
        },
    },

    # Define the loggers
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

and in my function a call

logger = logging.getLogger('django')
logger.info("Test!!")

this solution write the string “Test!!” but write all level info stuff to.
It is the wrong approach? or something is missing me?

Gonçalo Marques

Well, it’s kinda the right approach.

Your getLogger statement gets an instance of a Logger associated with a name. That name is used to find the appropriate entry in the loggers configuration dict.

However, the name you picked happens to be the name that Django itself uses as well.

If you want an isolated log with just your data, change the name of the loggers entry in your settings and change your getLogger call to get a logger for that name. (Make it unique!) You can then use that getLogger call (with that same name) across multiple apps / files to have it all logged to the same destination.

If you’re also going to leave existing loggers active, you might also want to assign a different handler for your custom log. (different log file name, etc)

Oohh i thought i wqw close. Thanks you very mutch!!