3

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?

gwydion93
  • 1,681
  • 3
  • 28
  • 59
  • 1
    Use `fileName=logFileName` and don't handle the file yourself. `logger.debug("Test")` will write to log file, no need to do anything besides that. BTW `logger.{debug,info,warning,error}` methods don't return, that's why you see `None` in file. – hoefling Aug 30 '19 at 00:44

1 Answers1

7

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

Calculus
  • 781
  • 7
  • 20
  • 1
    This totally worked. I don't quite understand why my code didn't work. Is it because you have to have a `fileHandler`? Did using `'name'` screw things up? Does it matter that I use `.txt` instead of `.log`? I'm still confused, but your solution works in my code. – gwydion93 Aug 30 '19 at 14:17