logger.exception will output a stack trace alongside the error message.

For example:

import logging
try:
    1/0
except ZeroDivisionError:
    logging.exception("message")

Output:

ERROR:root:message
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

@Paulo Cheque notes, "be aware that in Python 3 you must call the logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that."

Answer from SiggyF on Stack Overflow
🌐
Medium
medium.com › @rahulkumar_33287 › logger-error-versus-logger-exception-4113b39beb4b
Python Logging — logger.error versus logger.exception | by Rahul Kumar | Medium
October 25, 2021 - There are subtle differences which I stumbled onto recently although I have used Logging module for as long as I have been writing Python. Here is the code below with 3 ways of logging when somethings goes wrong (there could be more ways of course, but for sake of the point of this post, I will restrict to them) ... Notice that while this gives a nicely formatter ERROR log, it suppresses the traceback information since we have set our log formatter to output log message on stdout in the format ‘%(asctime)-15s %(levelname)-2s %(message)s’. logger.error(e, stack_info=True, exc_info=True) will give you that nicely formatted ERROR message in addition to the Traceback and Stack.
Discussions

logging - How can I log current line, and stack info with Python? - Stack Overflow
Instead of doing stack_trace[:-1] (which means it needs to format one frame more than you use, then slice the result), couldn't you do: frame = inspect.currentframe(1) so you get the stack without the top layer, so format_stack doesn't need to process it, and the return from format_stack requires no manipulation? 2016-03-04T20:43:13.123Z+00:00 ... Save this answer. ... Show activity on this post. As of Python ... More on stackoverflow.com
🌐 stackoverflow.com
logging - Python - How to print stack trace at all log levels and even outside exceptions? - Stack Overflow
My codebase is extremely large, and we’d like to print the stack for all logs. This includes logs at all levels (even INFO and DEBUG). This also includes logs outside of an exception happening. Thi... More on stackoverflow.com
🌐 stackoverflow.com
How can I use Try Except without hiding the stack trace?
repr doesn't give you all the info in the exception. Look at the traceback module for printing them more formatted with full stacktrace. Look at the rich package on PyPI if you want really fancy formatting and colors. More on reddit.com
🌐 r/pythontips
9
3
September 19, 2025
Why and how to hide the Python stack trace
This post was mass deleted and anonymized with Redact one silky correct different reach support march quack fade bear More on reddit.com
🌐 r/Python
6
0
June 3, 2023
🌐
Real Python
realpython.com › lessons › capturing-stack-traces
Capturing Stack Traces (Video) – Real Python
But basically, Python will try to divide 5 by 0, realize that it can’t, and then instead of just crashing, it will first log the exception. 00:59 That’s the last line that says logging.error('Exception occurred', exc_info=True). 01:08 Now, when we look at the output, we’ll see the standard log output for an error, as well as the stack trace beneath it.
Published: July 23, 2019
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
Source code: Lib/traceback.py This module provides a standard interface to extract, format and print stack traces of Python programs. It is more flexible than the interpreter’s default traceback di...
🌐
Better Stack
betterstack.com › community › questions › how-log-python-error-with-stack-trace
How to log a Python error with debug information (stack trace) | Better Stack Community
May 1, 2023 - When you encounter an error in your code, you can log it along with its stack trace using the logging.exception() method. This method logs the error message along with the traceback.
🌐
Linux Hint
linuxhint.com › print-stacktrace-python-log
Print Stacktrace in Python Log – Linux Hint
The following methods are used to log the error and print the Stacktrace in a Python log: ... The “traceback.print_exc()” method of the “traceback” module is used to print the Stacktrace.
🌐
EyeHunts
tutorial.eyehunts.com › home › python log stack trace
Python log stack trace - Tutorial - By EyeHunts
July 11, 2023 - To log a stack trace in Python, you can use the traceback module along with a logging framework like logging.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › logging.html
logging — Logging facility for Python
The name of the function or method which invoked the logging call. ... A stack traceback such as is provided by traceback.print_stack(), showing the call hierarchy.
🌐
SentinelOne
sentinelone.com › blog › data platform › python stack trace: understanding it and using it to debug
Python Stack Trace: Understanding it and Using it to Debug
October 27, 2022 - A stack trace report contains the function calls made in your code right before the error occurred. When your program raises an exception, it will print the stack trace. Below is an example of a simple Python script that will raise an exception.
🌐
Delft Stack
delftstack.com › home › howto › python › python print stack trace
How to Print Stack Trace in Python | Delft Stack
March 11, 2025 - When an exception occurs, we call logging.error() with the message and set exc_info=True to include the stack trace in the log. This method is particularly useful for long-running applications where you want to keep a record of errors without cluttering the console output. Printing stack traces in Python is an essential skill for debugging and error handling.
🌐
Loggly
loggly.com › home › blog › exceptional logging of exceptions in python
Exceptional Logging of Exceptions in Python - Loggly
October 25, 2022 - In Python 2, the “raise … from” syntax is not supported, so your exception output will include only the stack trace for NoMatchingRestaurants. The Transformer pattern is still perfectly useful, of course. In this pattern, you log that an exception occurs at a particular point, but then allow it to propagate and be handled at a higher level:
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Explanation: The except block catches the exception and uses traceback.format_exc() to capture the complete error traceback as a string. This error message is then stored in error_msg and printed, providing detailed debugging information about where the error occurred. logging module's logging.exception() method logs the error message along with the full stack trace, making it ideal for production environments.
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - The inspect.getinnerframes function returns a list of FrameInfo objects, each of which contains the details of a single frame in the stack trace, including the filename, line number, function, and code context. Inside the for loop, we retrieve each of these and then print them, using a format that mimics Python’s default stack trace printouts.
🌐
Finxter
blog.finxter.com › how-to-log-a-python-error-with-debug-information
How to Log a Python Error with Debug Information? – Be on the Right Side of Change
September 21, 2021 - Python provides us with a logging ... The logging module has various functions to get detailed information like the line number, stack traces to the line where the error occurred....
🌐
Sentry
sentry.io › sentry answers › python › analyze python stack traces
How to Read Python Stack Traces and Tracebacks | Sentry
August 15, 2024 - Read Python stack traces bottom-to-top to find the error, then trace the call chain through your code and library frames to identify the root cause
Top answer
1 of 1
3

You are on the right track. I recommend that you read the logging HOWTO, it explains a lot of things.

You can use levels and filters to decide if your handler should handle or not the log. And you can use a Formatter to add the stacktrace to the log record message.

Here is a Proof-of-Concept :

import logging
import traceback
import sys


logger = logging.getLogger("app.main")


class StacktraceLogFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        stack_lines = traceback.format_stack()
        # we have the lines down to ^^^^^^ this call, but we don't want to show it, nor the internal logging ones
        stack_lines_without_logging_intermediary_calls = filter(
            lambda line: ("lib/logging/__init__.py" not in line)
                         and ("lib\\logging\\__init__.py") not in line,
            stack_lines[:-1]
        )
        return record.msg + "\nOrigin :\n" + "".join(stack_lines_without_logging_intermediary_calls)
        # beware of : https://stackoverflow.com/q/8162419/11384184


class InfoOrLessFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        return record.levelno <= logging.INFO


def do_some_logging():
    logger.debug("debug message")
    logger.info("info message")
    logger.warning("warning message")
    logger.error("error message")
    try:
        1/0
    except ZeroDivisionError:
        logger.exception("exception message")
    logger.critical("critical message")


def setup_custom_logging():
    logger.handlers = []  # remove the existing handlers from the logger

    regular_handler_for_info_messages = logging.StreamHandler(sys.stdout)
    regular_handler_for_info_messages.setLevel(logging.DEBUG)  # at least DEBUG
    regular_handler_for_info_messages.addFilter(InfoOrLessFilter())  # but not more than INFO
    logger.addHandler(regular_handler_for_info_messages)

    stacktrace_handler_for_important_messages = logging.StreamHandler(sys.stderr)
    stacktrace_handler_for_important_messages.setLevel(logging.INFO + 1)  # more than INFO
    stacktrace_handler_for_important_messages.setFormatter(StacktraceLogFormatter())
    logger.addHandler(stacktrace_handler_for_important_messages)

    logger.propagate = False


def main():
    logging.basicConfig(level=logging.DEBUG)
    do_some_logging()
    setup_custom_logging()
    do_some_logging()


if __name__ == "__main__":
    main()

It produces before :

debug message
info message
DEBUG:app.main:debug message
INFO:app.main:info message
WARNING:app.main:warning message
ERROR:app.main:error message
ERROR:app.main:exception message
Traceback (most recent call last):
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 43, in do_some_logging
    1/0
ZeroDivisionError: division by zero
CRITICAL:app.main:critical message

and after :

warning message
Origin :
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 73, in <module>
    main()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 69, in main
    do_some_logging()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 40, in do_some_logging
    logger.warning("warning message")

error message
Origin :
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 73, in <module>
    main()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 69, in main
    do_some_logging()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 41, in do_some_logging
    logger.error("error message")

exception message
Origin :
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 73, in <module>
    main()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 69, in main
    do_some_logging()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 45, in do_some_logging
    logger.exception("exception message")

critical message
Origin :
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 73, in <module>
    main()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 69, in main
    do_some_logging()
  File "C:/PycharmProjects/stack_overflow/67846424.py", line 46, in do_some_logging
    logger.critical("critical message")
🌐
AppSignal
appsignal.com › learning-center › understanding-python-error-messages
Understanding Python error messages and stack traces | AppSignal
September 7, 2023 - With AppSignal, you can automatically ... visibility into issues as they occur: Whenever an error occurs in your application, Python will raise an exception and log a stack trace, which you can then use to find the location of ...
🌐
GitHub
github.com › trawick › stacktraces.py
GitHub - trawick/stacktraces.py: Python-based stack trace analysis tools · GitHub
Stack traces (backtraces) can be obtained from the following: live process or core file via gdb or Solaris pstack ... The software builds a representation of the available data which can be output as JSON or as text.
Author: trawick
🌐
PyPI
pypi.org › project › mo-logs
mo-logs · PyPI
trace - Show more details in every log line (default False) cprofile - Used to enable the builtin python c-profiler, ensuring the cprofiler is turned on for all spawned threads.
      » pip install mo-logs
    
Published: Mar 02, 2026
Version: 8.703.26061