I'm on Windows 10 using VS Code 1.73.1 and am retrofitting my program with the Python logging
module. My program is generally functioning. The main thing I did is change all the print statements to logger.debug
and I know the variable formatting needs to be changed from {}
to %s
. I also added the encoding
flag to my file handler.
A couple more things:
F5
function to run it, it does NOT create a file or display any console output anywhere. print('something')
works and displays in either the Terminal or Debug Console depending on the launch.json
setting, but logger.debug('something')
does not display in either console.
My request/question: Using logger.debug
, why is nothing printing to console, and no file is even created?
I also tried running the code below in its own separate .py
file with the same problem:
print
displays to the Debug Console, but logger.debug
does not.
Logging code block:
import logging
# Create a custom logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Streaming Handler
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.INFO)
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
logger.addHandler(c_handler)
# File Handler
f_handler = logging.FileHandler('download_shelf.log', encoding='utf-8')
f_handler.setLevel(logging.DEBUG)
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_format)
logger.addHandler(f_handler)
logger.debug(f"Log messages:") ### `print` statement displays in either the Terminal
### or Debug Console depending on `launch.json` setting
I made sure my launch.json
file was set up in the local .vscode
folder (see bottom code section). However, I did have to manually create this file, then restarted VS Code. Information I found said there was a link in the Debug panel, which I know I've seen before. It wasn't there for this file.
My directory structure:
toplevel/
.vscode/
launch.json
src/
subdirectory/
myfile.py
My launch.json
file contains "console": "internalConsole"
{
"configurations": [
{"name":"Python: Current File",
"type":"python",
"request":"launch",
"program":"${file}",
// "console":"integratedTerminal",
"console": "internalConsole",
"justMyCode":true
},
]
}
After using a different logger example, I realized the problem was the Level setting in the first example I used had "INFO" and not "DEBUG" so nothing was showing up. Oops...
import logging
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(level=logging.DEBUG)
formatter = logging.Formatter('%(levelname)s : %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.debug('simple message')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.