[Fixed]-Django: logging only for my project's apps

13👍

Not sure if I fully understood your question, because the answer seems too simple.

Assuming you have defined in LOGGING a handler for your project’s apps, for example like this:

'handlers': {
    'handler_for_my_apps': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': 'debug.log',
    },

and given your apps app1, app2, and so, you could have all the logs from those apps without any Django’s internal logs by defining the loggers:

'loggers': {
    'app1': {
        'handlers': ['handler_for_my_apps'],
        'level': 'DEBUG',
    },
    'app2': {
        'handlers': ['handler_for_my_apps'],
        'level': 'DEBUG',
    },

There will be no Django logs in the same file, unless of course you defined a logger named django with a handler handler_for_my_apps.

In your apps you can get the logger using logging.getLogger(__name__) as recommended by the docs.

Unless I misunderstood your question…

👤janos

22👍

You could use a scheme like the following to create identical loggers for all of your local apps without having to manually add them all to the logging configuration.

First, split out your local apps:

LOCAL_APPS = [
    'myapp1',
    'myapp2',
    ...
]

THIRD_PARTY_APPS = [
    'django. ...',
    ...
]

INSTALLED_APPS = LOCAL_APPS + THIRD_PARTY_APPS

Next create the logger configuration for your local apps:

local_logger_conf = {
    'handlers': ['my_handler',],
    'level': 'DEBUG',
}

Finally, define your loggers as follows:

'loggers': { app: copy.deepcopy(local_logger_conf) for app in LOCAL_APPS }
👤alanwj

2👍

Thank you for sharing, reading this post helped solve logging for my project. I’ll share the solution I opted for, hoping it can help other people.
Define a list of Dictionaries:

LOCAL_APPS = [
   {'app_name': 'app1', 'level': 'INFO'},
   {'app_name': 'app2', 'level': 'DEBUG'},
   ]

Now create a function to modify settings’ LOGGING:

def create_app_logger(app_name, level):
    app_handler = app_name + '_handler'
    LOGGING['handlers'][app_handler] = {
        'level': 'INFO',
        'class': 'logging.FileHandler',
        'filename': f'../logs/{app_name}_logs.log',
        'formatter': 'custom',
    }
    LOGGING['loggers'][app_name] = {
        'handlers': ['console', app_handler],
        'level': level,
        'propagate': False,
    }

Finally loop through the list:

for dictionary in LOCAL_APPS:
    create_app_logger(dictionary['app_name'], dictionary['level'])

Since an app can be a world on it’s own, this way you’ll have a log file for each app, plus you have control over the logging level you want. It could be further personalized of course.

Cheers

Leave a comment