Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Creating a Custom Logger

Give Feedback

In this lesson, you’re going to get some hands-on practice. You’re going to create a custom logger as well as some handlers that will represent output destinations.

Then, you’ll attach formatters to those handlers so you can independently format your logging output based on destination. After all that, you’ll attach those handlers to the logger so that you can use it. Basically, you’re going to create a bunch of objects and then wire them together to form a logging system.

Najmeh on Aug. 15, 2019

Thanks for the great video and explanation.

Fahim on Nov. 7, 2019

Hi,

I am getting below error for mentioned code.

Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'level'
Logged from file python-logging.py, line 20
Traceback (most recent call last):
  File "python-logging.py", line 20, in <module>
    logger.warning("This is warning")
  File "/usr/lib/python2.7/logging/__init__.py", line 1179, in warning
    self._log(WARNING, msg, args, **kwargs)
  File "/usr/lib/python2.7/logging/__init__.py", line 1286, in _log
    self.handle(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 1296, in handle
    self.callHandlers(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 1335, in callHandlers
    if record.levelno >= hdlr.level:
AttributeError: 'Formatter' object has no attribute 'level'

Here is my complete code

import logging

logger = logging.getLogger(__name__)


c_handler = logging.StreamHandler()
f_handler = logging.FileHandler("File.log")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.ERROR)

c_format = logging.Formatter('%(name)s - %(level)s - %(messeage)s')
f_format = logging.Formatter('%(asctime)s - %(name)s - %(level)s - %(messeage)s')

c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

logger.addHandler(c_handler)
logger.addHandler(f_format)

logger.warning("This is warning")
logger.error("This is error")

Fahim on Nov. 7, 2019

Hi,

I am getting below error for mentioned code.

Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'level'
Logged from file python-logging.py, line 20
Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'level'
Logged from file python-logging.py, line 21
Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'level'
Logged from file python-logging.py, line 21```

Here is my complete code

import logging

logger = logging.getLogger(name)

c_handler = logging.StreamHandler() f_handler = logging.FileHandler(“File.log”) c_handler.setLevel(logging.WARNING) f_handler.setLevel(logging.ERROR)

c_format = logging.Formatter(‘%(name)s - %(level)s - %(messeage)s’) f_format = logging.Formatter(‘%(asctime)s - %(name)s - %(level)s - %(messeage)s’)

c_handler.setFormatter(c_format) f_handler.setFormatter(f_format)

logger.addHandler(c_handler) logger.addHandler(f_handler)

logger.warning(“This is warning”) logger.error(“This is error”)

```

Fahim on Nov. 7, 2019

I figure it out. There was some silly spelling mistakes.

amern2k16 on Dec. 6, 2019

c_handler = logging.StreamHandler() The video says StreamHandler() is a method. I believe it’s a class? Aren’t we instantiating object in above statement?

techdiverdown on April 16, 2020

The logger by default is at level INFO, so if a handler has a lower level like DEBUG, the message will not appear as it will be filtered. The solution is to set a low level in the logger and then the handler can set whatever other levels and it will work as intended.

logger = logging.getLogger(‘foo’)

Note set to debug on the logger then each handler can have another level

logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s’) ch.setFormatter(formatter) logger.addHandler(ch)

only write errors to file

fh = logging.FileHandler(‘log.txt’) fh.setLevel(logging.ERROR) fh.setFormatter(formatter) logger.addHandler(fh)

logger.debug(“debug”) logger.info(“info”) logger.warning(“warning”) logger.error(“error”) logger.critical(“critical”)

Patrick Prince on April 26, 2020

Hi,

I’m getting the following error -> Traceback (most recent call last): File “H:\python\samples\logging.py”, line 8, in <module> import logging File “H:\python\samples\logging.py”, line 11, in <module> logger = logging.getLogger(‘fdf2pdf_v6.py’) AttributeError: module ‘logging’ has no attribute ‘getLogger’

Source Code was copied from Course Materials ->

import logging

Create a custom logger

logger = logging.getLogger(‘fdf2pdf_v6.py’)

Patrick Prince on April 26, 2020

Regarding my comment above, oddly, the code runs without errors in ipython.

singh07 on June 29, 2020

I am getting below output:

__main__ - WARNING - This is a warning.
ERROR:root:This is a error.

and nothing in File.log. Here is my file. Could you please guide me what is wrong here.

import logging

logger = logging.getLogger(__name__)

c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('File.log')
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.ERROR)

c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

logger.addHandler(c_handler)
logger.addHandler(f_handler)

logger.warning('This is a warning.')
logging.error('This is a error.')

ed6 on Aug. 11, 2020

There is a an error in the code. This does NOT work if you set logger.info or logger.debug. Nothing will show even if you change the levels. You have to do as techdiverdown says and set the root logger to DEBUG and then the file handlers levels can then be set from there. Otherwise, you will only be able to see the WARNING level and above messages.

Become a Member to join the conversation.