很好的博客:python 日志 logging模块(详细解析)
1、仅在控制台打印日志信息
import logging
def add(x, y):
return x + y
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format='[%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
logger.info("Start print log")
sum = add(2, 3)
logger.info(f"sum is {sum}")
logger.info("End print log")
[INFO] Start print log
[INFO] sum is 5
[INFO] End print log
2、仅在日志文件中打印日志信息
import logging
def add(x, y):
return x + y
if __name__ == "__main__":
logging.basicConfig(
filename="log.txt",
level=logging.INFO,
format='[%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
logger.info("Start print log")
sum = add(2, 3)
logger.info(f"sum is {sum}")
logger.info("End print log")
[INFO] Start print log
[INFO] sum is 5
[INFO] End print log
3、同时在控制台和日志文件中打印日志信息
在 logger 中添加 StreamHandler,可以将日志信息输出到控制台上。
import logging
def add(x, y):
return x + y
if __name__ == "__main__":
logging.basicConfig(
filename="log.txt",
level=logging.INFO,
format='[%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
console = logging.StreamHandler()
logger.addHandler(console)
logger.info("Start print log")
sum = add(2, 3)
logger.info(f"sum is {sum}")
logger.info("End print log")
Start print log
sum is 5
End print log
[INFO] Start print log
[INFO] sum is 5
[INFO] End print log
可以发现此时控制台的日志信息并没有被格式化为指定格式。
|