2015-06-25 11 views
5

Ho creato un TimedRotatingHandler per il server Flask. Ma tutti i log generati dal werkzeug vengono comunque lanciati sulla console.Come reindirizzare i log werkzeug di python in un file di registro quando si utilizza TimedRotatingHandler?

Come reindirizzare questi registri al file di registro (test.log) con la funzionalità di rotazione del registro.

Codice frammento:

log = logging.getLogger(__name__) 
log.setLevel(logging.DEBUG) 
# add a file handler 
fh = logging.handlers.TimedRotatingFileHandler("test.log",when='M',interval=1,backupCount=0) 
fh.setLevel(logging.DEBUG) 
# create a formatter and set the formatter for the handler. 
frmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 
fh.setFormatter(frmt) 
# add the Handler to the logger 
log.addHandler(fh) 
app.run(host='0.0.0.0', debug=True) 

I registri che seguono sono ancora gettati sulla console.

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) 
* Restarting with stat 
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET/HTTP/1.1" 200 - 
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /static/js/jquery-1.11.2/jquery-1.11.2.min.js HTTP/1.1" 304 - 
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /static/js/main/main.js HTTP/1.1" 304 - 
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /favicon.ico HTTP/1.1" 404 - 

Aggiungendo il gestore di file di log al logger werkzeug non è troppo risolvere il problema

logging.getLogger('werkzeug').addHandler(fh); 

risposta

1

Sembra werkzeug invia messaggi al logger principale, piuttosto che un logger di nome.

Se si tenta questo dovrebbe iniziare accedendo al file logging.getLogger().addHandler(fh)

Se si desidera interrompere la registrazione alla console, allora si dovrà rimuovere il gestore flusso dal logger principale. È possibile vedere i gestori per il logger principale utilizzando

>>> print logging.getLogger().handlers [<logging.StreamHandler object at 0x.....>, logging.handlers.TimedRotatingFileHandler object at 0x.....>]

-1

Per cambiare werkzeung la registrazione è necessario eseguire l'override logging.root.handler come:

import logging 
from logging.handlers import RotatingFileHandler 

handler = RotatingFileHandler('log.log', maxBytes=10000, backupCount=1) 
handler.setLevel(logging.ERROR) 

logging.root.handlers = [handler] 

Vedi here per i dettagli.

Problemi correlati