0

I have written this code in log.py.

import logging
import os


# make directory
directory = 'logs'
if not os.path.exists(directory):
  os.makedirs(directory)

# create logger
logger = logging.getLogger('testfile')
logger.setLevel(logging.DEBUG)


loghandler = logging.FileHandler(directory + '\log.txt')

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to loghandler
loghandler.setFormatter(formatter)

# add loghandler to logger
logger.addHandler(loghandler)

Now, user can use this in any module like

import log
log.logger.warn("gjh")

3 Answers 3

3

You're creating a whole module for a single global object. If you want to save code, just have a function that creates it:

def make_logger():
  logger = logging.getLogger('testfile')
  # initializations...
  # ...
  return logger

logger = make_logger()
logger.warn('ghj')

With keyword arguments and default values, you can also easily customize its creation if such a need arises (and it probably will arise as your program gets more complex).

Sign up to request clarification or add additional context in comments.

2 Comments

But, won't it create a new object every time I call make_logger() from different modules? Does it not matter?
@ruskin: so use an object and pass around a reference to it. I would still not make a module just for the logging object. Some top-level object/module must be creating the logger anyway, so it can "own" it and pass around to other modules needing it
2

I see a couple of problems

  1. Apparently you are indenting using two spaces and this is a crime in Python
  2. You are using '\log.txt' that works just because a lowercase L has no special meaning as a control character. Better to use the os-specific path construction function instead (see os.path.join)

Comments

1

regarding the coding style I would recommend to use dedicated tools. There have been some posts before, for example this one: PyLint, PyChecker or PyFlakes?

Personally I prefer to use pylint with a configuration file adapted to some things that I want to be followed in my projects (e. g. special variable names). If you want to have a quick look, try pep8.

Best regards, Rainer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.