Solvedloguru Change level of default handler

First off, this library is terrific, I found it via the podcast Python Bytes and I've been using it ever since.

So here is my question: I understand, the default handler for from loguru import logger goes to sys.stderr.

When I try: logger.add(sys.stderr, level="INFO"), I still get DEBUG level messages in the terminal.

My goal is to change the level of the logging to sys.stderr. I don't have any other handlers.

19 Answers

โœ”๏ธAccepted Answer

@Delgan Thank you! I've got

log.remove()
log.add(sys.stderr, level=config.LOG_LEVEL)

in my codebase now. I missed that the .remove() method removes the previously added handler (meaning the default one). For some reason I thought I'd have to know the default handler's id.

Other Answers:

@jetheurer If no argument is provided to logger.remove(), all existing handlers are removed.

You can also remove the default handler using logger.remove(0), because the default handler will always have the id 0.

Just to be clear, I think @Delgan is recommending that folks do this via the env. Without setting the env, you are defaulted to debug mode for development. Then in production you set LOGURU_LEVEL in the environment. To change the level in development to see what prod logs look like, you can just do:

LOGURU_LEVEL=INFO python my_script.py

Hello @jetheurer, happy to know that you like Loguru ! ๐Ÿ˜ƒ

So, indeed, by default a sys.stderr handler is added with an "INFO" level.

You can add as many handlers as you want, this means that if you do logger.add(sys.stderr, level="INFO") while the default handler has not been removed, your log messages will be dispatched twice to sys.stderr!

This is why you still see DEBUG messages. Those are the one from the default handler which co-exists with your INFO handler.

The solution is to first .remove() the default handler, before adding a new one which logs to stderr.

Alternatively, you can set the LOGURU_LEVEL environment variable to "INFO", so the default handler will be started with your preferred level all the times.

Hi @RichardDally. :)

The rational behind setting the default level to DEBUG is as follow: every new project first goes through a development phase during which debug messages are much helpful. As a loguru user, you will spend most of your time developping your application. When your software is fully working and ready to release, you can take the time to properly add handlers and configure the level based on a command line argument for example.

So it makes sense, from my point of view, that you can start any Python application and see debug messages without any further configuration.

from loguru import logger

logger.debug("Let's go to work")

If you want to replace standard logging with Loguru, you also need to replace logger.addHandler() and others setup steps, right? So, could you not simply use logger.add(sys.stderr, level="INFO")?

Related Issues:

28
loguru How to set the log level?
I you would like to use another level in place of the default DEBUG you can just set the LOGURU_LEVE...
18
loguru Change level of default handler
@Delgan Thank you! I've got in my codebase now I missed that the .remove() method removes the previo...
188
laravel activitylog >PHP7.2: Declaration of Orchestra\Testbench\TestCase::setUp() must be compatible with PHPUnit\Framework\TestCase::setUp()
@AndresMatta in TestCase.php file add :void public function setUp(): void phpunit --coverage-text --...
70
LogViewer Log [] is not defined. Unable to create configured logger. Using emergency logger.
If you're using Laravel 5.6 you need to update your config files if you've migrated from an older la...
66
CocoaLumberjack Xcode 9 beta 3 breaks the new os_log logger
Getting the following errors DDOSLogger.m: DDOSLogger.m:58:17: Static_assert failed format argument ...
23
fluent bit Errors when forwarding to ElasticSearch
@edsiper I've got the same problem also related to es_rejected_execution_exception but: It should st...
19
fluent bit Duplicate @timestamp fields in elasticsearch output
@edsiper I would reopen this I have this config: and keep getting error like this one: ...
13
fluent bit Add S3 bucket Output plugin
@fujimotos @amit-uc @tarunwadhwa13 @eyalengel-pagaya @kmajic A Pre-release version is now available!...
11
fluent bit Docker_mode to recombine multiline records in json-log from docker
@sumo-drosiek I finally able to get it working I will left an example here for future reference ...
11
fluent bit systemd input not showing in output
I found a little time to dig into the source code and the issue is obvious now The plugin uses syste...
6
fluent bit Using multiple filters for the same record - is it possible?
@edsiper I think that should be enough Main use cases for me: read logs from specified namespaces on...
4
matomo User-ID: Unique Visitor is not recognized even with the same User-ID
Is this really what we want? In this case the User-ID has no more added value than a named CustomDim...
4
monolog bundle excluded_404s does not work for symfony 3
@zerkms Thanks a million This led me in the right direction If anybody stumbles over this ...
3
matomo JS Tracker: Add possibility to turn cookies back on, enableCookies
If the page is reloaded and disableCookies isn't pushed the cookies should be automatically used aga...
12
pino Map log levels to StackDriver's severity
The formatters introduced in v6 works great with GCP / StackDriver logging Example mapping: ...
92
debug npm WARN enoent ENOENT: no such file or directory, open '<root>/node_modules/supertest/package.json'
No That's not an issue of debug package I think it's related to NPM v3's changed installation behavi...
34
logrus How to separate Stdout and Stderr output?
not supporting both stdout and stderr streams for logging IS NOT a narrow use case ...
31
logstash with java10 I get these error :Unrecognized VM option 'UseParNewGC'
I think the problem can be fixed for Java versions 9+ by changing 2 lines of code in the jvm.options...
27
logrus Should I use lowercase or uppercase for the package name?
So I ended up working around this by levering glide aliasing support Hi I am using two hooks ...
19
loki Docker driver doesn't work with warning "no logs are available with the 'loki' log driver"
@tam481 Thank you so much! I read this issue a lot but not carefully Describe the bug Docker driver ...
16
abseil py abseil interferes with python logging
The key issue however is that neither importing nor using absl.logging should reconfigure logging ...
13
loki Filtering out specific JSON keys from logs
In case someone is looking for this the syntax is message is the json field here. ...
12
abseil py pip install error when old setuptools versions used
I upgraded pip from ver 9.0.1 to current (20.2.3) and the problem got fixed To upgrade: pip install ...
12
fluentd buffer space has too many data errors on k8s cluster
I have the same issue surprisingly restart of fluend works for a while I would appreciate a guidance...
11
loki Promtail: Cant get the value of filename in relabel_configs
@rmgpinto I was trying to do roughly the same thing In relabel_configs I would like to get the filen...
5
debug Importing debug in angular 2 app with system.js
I took some inspiration from Importing lodash into angular2 + typescript application and finally fig...
4
spdlog Error trying to use the spdlog static library with cmake
So for the record (and a potentially future updated readme file...) I managed to build spdlog correc...
3
sigma Es-dsl and es-qs wildcards incorrect
Thank you for the information However I tested the outputs of the sigma es-dsl and es-qs but they ou...
926
keras Loading model with custom loss function: ValueError: 'Unknown loss function'
I solved this problem by adding 'custom_bojects' my loss function: I trained and saved a model that ...
731
scrapy ' error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 '
@euler16 for scrapy with Python 3 you'll need with Python 2 you'll need I wanted to install scrapy i...
633
keras Tensorflow backend - bug in model._make_predict_function(...)
I had this problem when doing inference in a different thread than where I loaded my model ...
575
mysqlclient Can't install mysqlclient on MacOS
You can set ssl library path explicitly. Hi I'm on MacOSX Sierra ...
516
keras Creating Model variable throws "AttributeError: 'Tensor' object has no attribute '_keras_history'"
@zaid478 oh I assumed you were doing it on coursera Anyway Hello all setup: Keras 2.0 Tensorflow 1.0...
456
tensorflow ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory
@rhinsall I just found this out myself not sure if it's common knowledge but got around this by doin...
423
ipython Last jedi release (0.18.0) is incompatible with ipython (7.19 and 7.18 tested); reason - column arg was deprecated, and now removed
As a temporary fix for anyone just trying to get things working again: It would be really nice if yo...
416
pyodbc pip install pyodbc failing: error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
src/pyodbc.h:56:17: fatal error: sql.h: No such file or directory #include <sql.h> ^ Your machine do...
395
keras "<tensor> is not an element of this graph." when loading model.
I had a problem similar to that of @piraka9011 which was solved by calling model._make_predict_funct...
392
psycopg2 psycopg2-binary fails to install on macOS Big Sur 11.0.1 and Python 3.9.0 (with possible workaround)
Actually figured it out Haven't worked on a Mac in a while and forgot about the PostgreSQL dependenc...
387
pytorch I can't import PyTorch, libomp.dylib can't be loaded.
brew install libomp solves the problem. ๐Ÿ› Bug I tried to install PyTorch but I can't use it ...
380
pytorch RuntimeError: cuda runtime error (59) : device-side assert triggered when running transfer_learning_tutorial
@soumith Hi I find the error it is due to my labels contain value -1 which is unacceptable in criter...
373
Zappa bad magic number in 'application': b'\x03\xf3\r\n': ImportError
I was able to fix this too by doing find -name \*.pyc -delete Mine definitely wasn't caused by PY2 -...
356
tensorflow At Runtime : "Error while reading resource variable softmax/kernel from Container: localhost"
I had the same issue in tensorflow 1.13.1 which I have resolved by creating a reference to the sessi...
355
tensorflow Mac + Python 3.6.1: Attempting to download mnist data results in CERTIFICATE_VERIFY_FAILED error
This might have also been because I recently switched to a new machine and it's still only partially...
335
pyenv WARNING: pyenv init - no longer sets PATH.
I saw the same message on an RH derivative Linux using bash 4.4.19 To resolve After running pyenv up...
333
pyenv unable to install python 3.8.0 on macox 11
Try to install brew reinstall zlib bzip2 and in the ~/.zshrc file add the following: in case you are...
331
psutil psutil fails to install on python3.6 and Ubuntu16.04
I was just about to comment the same after I read the install file: https://github.com/giampaolo/psu...
326
psycopg2 Installing psycopg2-binary with Python:3.6.4-alpine doesn't work
I found this solution which worked quite fine Edit The above compiles the package from source so I w...
325
pyenv Unable to build Python on macOS Big Sur with Xcode 12 beta
Thank you HomeBrew team for all the hard work you did to find the patch that python team is brewing ...