简体   繁体   中英

How to write logging messages to a file

I am trying to use the Python logging library. Instead of printing the messages in the console, I want to write them to a file. Based on the documentation , I'm a little unsure of how to do this. First I imported the logging in and then I created my logging object. Note: I am a little unsure of the name parameter when doing this. Is this suppose to be a filename that has a full filepath? A random name that I just make up?

foldname = "chk_logs"
logFileName = os.path.join(path.abspath(path.curdir),foldname + "\\Fields_Log_" + timeStamp + ".txt")             #logging
if os.path.isdir(foldname)==False:
    os.mkdir(foldname)
logFile = open(logFileName, "w")

format="%(asctime)s [%(levelname)s] %(message)s"
logging.basicConfig(fileName=logFile, format=format, level=10)
logger = logging.getLogger('name')  

So, suppose I want to write a message to the logFile from my logger .

   logger.debug("Test")

This essentially does nothing, even after I use logFile.close() . If I try this:

logFile.write(str(logger.debug("Test")))

it basically write 'None' in the .txt file. There must be a simple way to do this; what am I doing wrong?

Here's some boilerplate code I always use for Python logging. This is for Windows. If you're using UNIX you'll need to change the forward slashes to backslashes

import os
import logging
import datetime as dt
import time

LOG_FILE = os.getcwd() + "/logs"
if not os.path.exists(LOG_FILE):
    os.makedirs(LOG_FILE)
LOG_FILE = LOG_FILE + "/" + dt.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d %H_%M_%S') + ".log"
logFormatter = logging.Formatter("%(levelname)s %(asctime)s %(processName)s %(message)s")
fileHandler = logging.FileHandler("{0}".format(LOG_FILE))
fileHandler.setFormatter(logFormatter)
rootLogger = logging.getLogger()
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.INFO)

logging.info("testing out the logging functionality")

You should end up with a log file that has a date timestamp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM