Logging messages to file in Python not working when running outside interactive mode in VS Code

145 Views Asked by At

I have a simple Python code that logs messages to a file using the logging module. However, when I run this code in Visual Studio Code (VS Code) outside of the interactive mode, I do not see any logs in the file. Strangely, when I run the same code in the interactive mode, the logs are successfully written to the file. Here is my code:

import logging

# Configure logger for use case 1
logger1 = logging.getLogger('use_case_1')
logger1.setLevel(logging.INFO)

# Create file handler for use case 1
handler1 = logging.FileHandler('./use_case_1.log', 'a')
formatter1 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler1.setFormatter(formatter1)
logger1.addHandler(handler1)

# Create stream handler for use case 1 (console)
console_handler1 = logging.StreamHandler()
console_handler1.setFormatter(formatter1)
logger1.addHandler(console_handler1)

# Usage example
logger1.info('Log message for use case 1')
handler1.flush()  # Flush the file handler

I would like to understand the difference between running the code in VS Code outside the interactive mode versus running it in the interactive mode, and why I am not getting any logs when running outside of the interactive mode. Any insights or suggestions would be greatly appreciated.

1

There are 1 best solutions below

0
starball On

You're using relative paths, so the file location will depend on the cwd of the intepreter process. You could switch to absolute paths, or configure VS Code to have a consistent cwd for the different types of Python processes.

  • For Jupyter, use the jupyter.notebookFileRoot setting, which defaults to "${fileDirname}".

  • For the run file action and corresponding button, use the python.terminal.executeInFileDir setting, which toggles whether the cwd is the file directory or the workspace directory.

  • For tasks, use the "options" property's "cwd" property.

See also https://code.visualstudio.com/docs/editor/variables-reference.