Add 'Python log to a file'
parent
5b19059e46
commit
c8e2274e59
29
Python-log-to-a-file.md
Normal file
29
Python-log-to-a-file.md
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
```
|
||||||
|
import logging
|
||||||
|
import traceback
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# this raise an error
|
||||||
|
|
||||||
|
def err():
|
||||||
|
raise ValueError("This is not the expected value")
|
||||||
|
|
||||||
|
# configure the logger handler and formatter for the log file
|
||||||
|
|
||||||
|
logger = logging.getLogger("file_logger")
|
||||||
|
logger.setLevel(logging.DEBUG)
|
||||||
|
fh = logging.FileHandler("python_process.log")
|
||||||
|
fh.setLevel(logging.DEBUG)
|
||||||
|
ff = logging.Formatter(fmt='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')
|
||||||
|
fh.setFormatter(ff)
|
||||||
|
logger.addHandler(fh)
|
||||||
|
|
||||||
|
# Log known errors to a file. Logging all possible exceptions is not recommended
|
||||||
|
|
||||||
|
try:
|
||||||
|
err()
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(str(e))
|
||||||
|
logger.error(traceback.format_exc())
|
||||||
|
logger.error(sys.exc_info()[2])
|
||||||
|
```
|
Loading…
Reference in a new issue