Unos
Unos

Reputation: 1361

Avoid empty log files getting touched upon invoking Django management command

I have logging configured in my project.settings file as follows:

LOGGING = {
    [ . . . ],
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'logfile': {
            '()': uniq_logfile,
            'level': 'DEBUG',
            'formatter': 'verbose',
            'logtype': 'global',
        },
    [ . . . ]
}

Here is the definition of uniq_logfile:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def uniq_logfile(logtype):
    base = '%s.%s' % (logtype, datetime.datetime.now().strftime('%d%b.%H%M'))
    path = os.path.join(BASE_DIR, '.logs', base)
    return logging.FileHandler(path, 'w')

Problem: Whenever I run any ./manage.py <command>, all handlers are invoked and an empty log file for each handler is touched. For example, if I have 3 handlers defined, and I invoke a manage.py command that has only one associated handler, all 3 handlers are invoked (2 empty files are created corresponding to the other two handlers). Is there some setting to avoid doing that?

I am using python v2.7.10 on Mac.

Upvotes: 1

Views: 81

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99495

You don't say which version of Python you're using - in Python 2.6 and later, you can set the delay parameter to file handler constructors to avoid opening the files until something is actually going to be written to them. See the FileHandler documentation.

Upvotes: 1

Related Questions