Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Saving Logs to Files

Sound effect: Cat Meowing by theshaggyfreak – https://freesound.org/s/274989/ – License: Attribution 4.0

00:00 So far throughout the course, you’ve been logging to your console, and while that’s useful during development, in production you’ll typically want to write logs to files. Open a Python interactive session, and let’s import the logger object from the loguru module. If we inspect what we have inside this logger, we have the default handler that writes the output to the stderr.

00:26 When you call the .add() method to add a new handler, we’ll specify a different destination or sink. By passing the string app.log as the sink, all the log messages will be written to this file.

00:41 Because of this, in addition to logging to the console, a new file called app.log will also be created if it doesn’t exist, or it’ll be appended to if it does exist.

00:53 So now, if we log an info message, this message will go both to stderr and to the app.log file. So we see it in here, it was shown in stderr.

01:05 Now let’s leave the Python interactive session, and let’s inspect to see if we have this app.log file. We see that the file’s been created, now let’s see what’s inside of it by using the cat command.

01:23 And here you see that the app.log file is a basic text file that you can open in any text editor, and it contains the same info message that we saw in stderr.

01:33 So now you know how to send the logs to multiple destinations, such as files or standard error. You’ve seen how to configure, customize, and persist logs using loguru.

01:43 In the final lesson, I’ll briefly recap what you’ve learned until now, and point you toward a few ways you can continue improving your Python skills.

Become a Member to join the conversation.