How To Write Logs To A File With Python?

Better Stack Team
Updated on May 4, 2022

Using Basic Configuration

You can use basic config. If you configure the attribute filename, logs will be automatically saved to the file you specify. You can also configure the attribute filemode. Setting the value to w will overwrite the file after every entry.

import logging

logging.basicConfig(filename="logs.log", filemode="w", format="%(name)s -> %(levelname)s: %(message)s")

logging.warning("warning")

OUTPUT
root -> WARNING: warning
Copied!

Using Provided Classes

You can also use the provided classes - loggers and handlers:

logger = logging.getLogger(__name__)
FileOutputHandler = logging.FileHandler('logs.log')

logger.addHandler(FileOutputHandler)

logger.warning("Warning.")
Copied!

You will create a logger and a handler. When creating a handler, assign the class FileHandler and a file name as an attribute. Then set the handler to a logger:

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack