zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Python] Create a Log for your Python application

Pythonlog for create application your
2023-09-14 09:00:51 时间


Print statements will get you a long way in monitoring the behavior of your application, but logging will get your further. Learn how to implement logging in this lesson to generate INFO, WARNING, ERROR, and DEBUG logs for your application.

 

 

import sys
import getopt
import logging

# pass in: python3 my_log.py -l info

# Get command line options
# short: l:
# long: [log=]
opts, args = getopt.getopt(sys.argv[1:], "l:", ["log="])

print("opts", opts) #[('-l', 'info')]
print("args", args) #[]

# default log level
log_level="INFO"

for opt, arg in opts: #opt: -l, arg: info
    if opt in ("-l", "--log"):
        log_level = getattr(logging, arg.upper())

logging.basicConfig(filename="./demo.log", level=log_level, format='%(asctime)s %(levelname)s:%(message)s')


for i in range(0, 100):
    if i % 5 == 0:
        logging.debug('Found a number divisible by 5: {0}'.format(i))
    else:
        logging.info('At number {0}'.format(i))

logging.warning('Finished sequence')