How to change the default sanic log directory to a

2019-07-29 11:51发布

问题:

Sanic currently supports Linux log directory as /dev/log, and the log wouldn't work if the directory does not exist. How do I change the directory to a custom one?

回答1:

Sanic uses the regular standard library logging utility.

Per the documentation:

To use your own logging config, simply use logging.config.dictConfig, or pass log_config when you initialize Sanic app.

app = Sanic('test', log_config=LOGGING_CONFIG)

# or

logging.config.dictConfig(LOGGING_CONFIG)

Here is a good resource on logging in Python.

What you are looking for is the filename keyword.

LOGGING_CONFIG = {
    ...
    'filename': '/path/to/my/log'
    ...
}


回答2:

After going through documentation and trying various combination I found the following solution to be working, use the following dict and change value of file path were ever neccessary.

from sanic.log import DefaultFilter
import sys
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
    'accessFilter': {
        '()': DefaultFilter,
        'param': [0, 10, 20]
    },
    'errorFilter': {
        '()': DefaultFilter,
        'param': [30, 40, 50]
    }
},
'formatters': {
    'simple': {
        'format': '%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S'
    },
    'access': {
        'format': '%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: ' +
                  '%(request)s %(message)s %(status)d %(byte)d',
        'datefmt': '%Y-%m-%d %H:%M:%S'
    }
},
'handlers': {
    'internalFile': {
        'class': 'logging.FileHandler',
        'filters': ['accessFilter'],
        'formatter': 'simple',
        'filename': "temp/clickinternal.log"
    },
    'accessFile': {
        'class': 'logging.FileHandler',
        'filters': ['accessFilter'],
        'formatter': 'access',
        'filename': "temp/clickaccess.log"
    },
    'errorFile': {
        'class': 'logging.FileHandler',
        'filters': ['errorFilter'],
        'formatter': 'simple',
        'filename': "temp/clickerr.log"
    },
    'internal': {
        'class': 'logging.StreamHandler',
        'filters': ['accessFilter'],
        'formatter': 'simple',
        'stream': sys.stderr
    },
    'accessStream': {
        'class': 'logging.StreamHandler',
        'filters': ['accessFilter'],
        'formatter': 'access',
        'stream': sys.stderr
    },
    'errorStream': {
        'class': 'logging.StreamHandler',
        'filters': ['errorFilter'],
        'formatter': 'simple',
        'stream': sys.stderr
    }
},
'loggers': {
    'sanic': {
        'level': 'DEBUG',
        'handlers': ['internal','errorStream','internalFile', 'errorFile']
    },
    'network': {
        'level': 'DEBUG',
        'handlers': ['accessStream','errorStream','accessFile', 'errorFile']
    }
}
}



app.run(debug=True,log_config=LOGGING, host='0.0.0.0', port='8001')