344

By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors.

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: 
name: Graphics Device
major: 5 minor: 2 memoryClockRate (GHz) 1.0885
pciBusID 0000:04:00.0
Total memory: 12.00GiB
Free memory: 11.83GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
...
serv-inc
  • 35,772
  • 9
  • 166
  • 188
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99
  • 5
    tracking issue: https://github.com/tensorflow/tensorflow/issues/1258 – Yaroslav Bulatov Mar 11 '16 at 17:26
  • Tensorflow is still early alpha code and they're still working out the bugs for basic compatibility with numpy and pandas. So to knock out these warnings in a single blow, do `import warnings` then `warnings.filterwarnings('ignore')`, then run your tensorflow imports and and code that relies on the broken alpha-tensorflow code, then turn warnings back on via `warnings.resetwarnings()`. Tensorflow shouldn't be advertising a version name over 0.05 at this point in time. – Eric Leschinski Sep 24 '19 at 00:52
  • I have the same problem, but then with the C++ API of Tensorflow (Lite). Setting environment variables before loading TF does not help. Also no help from the official TF (Lite) forum: https://github.com/tensorflow/tensorflow/issues/58050 Sigh, it's Oct 2022 and this problem still persists. Anybody who knows a solution for C++? – Bart Oct 22 '22 at 07:47

20 Answers20

422

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed
craymichael
  • 4,578
  • 1
  • 15
  • 24
mwweb
  • 7,625
  • 4
  • 19
  • 24
244

2.0 Update (10/8/19) Setting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there was a reported issue for version 2.0 until 2.3.z fixed in 2.4 and later. If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:

import tensorflow as tf
tf.get_logger().setLevel('INFO')

In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example:

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

v0.12+ Update (5/20/17), Working through TF 2.0+:

In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | INFO             | [Default] Print all messages       
  1     | WARNING          | Filter out INFO messages           
  2     | ERROR            | Filter out INFO & WARNING messages 
  3     | NONE             | Filter out all messages      

See the following generic OS example using Python:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

You can set this environmental variable in the environment that you run your script in. For example, with bash this can be in the file ~/.bashrc, /etc/environment, /etc/profile, or in the actual shell as:

TF_CPP_MIN_LOG_LEVEL=2 python my_tf_script.py

To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

For 1.14 you will receive warnings if you do not change to use the v1 API as follows:

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

**For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):**

View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:

tf.logging.set_verbosity(tf.logging.ERROR)

The page additionally goes over monitors which can be used with TF-Learn models. Here is the page.

This doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow.

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

For the other, please see this answer which involves modifying source and rebuilding TensorFlow.

jordanbtucker
  • 5,768
  • 2
  • 30
  • 43
craymichael
  • 4,578
  • 1
  • 15
  • 24
  • the "I tensorflow" messages can be annoying, tf should provide some way of silencing them using api instead of rebuilding – physicist Aug 01 '18 at 16:41
  • 4
    This can also be done from command line: `export TF_CPP_MIN_LOG_LEVEL="3" && python your_code.py` – Andrew Hundt Aug 26 '18 at 02:58
  • It can also be run as `TF_CPP_MIN_LOG_LEVEL="3" python your_code.py` – craymichael Aug 27 '18 at 03:17
  • Is there a way to turn tensorflow warnings/errors into errors? – CMCDragonkai Aug 30 '18 at 05:04
  • I apologize for the delayed response. AFAIK there is not (trivial) way of doing such, may I ask what you would like to accomplish by doing such @CMCDragonkai? – craymichael Nov 18 '18 at 02:07
  • Using `tensorflow-gpu 1.14.0`. Recieved this output when called the function above `The name tf.logging.set_verbosity is deprecated. Please use tf.compat.v1.logging.set_verbosity instead.` `WARNING:tensorflow:From C:/.../NN.py:297: The name tf.logging.ERROR is deprecated. Please use tf.compat.v1.logging.ERROR instead.` Pleasing that there were no no warnings after these messages – A.Ametov Oct 06 '19 at 23:53
  • 1
    tf.logging.set_verbosity(tf.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL} worked for me – Amir Md Amiruzzaman Jan 13 '20 at 03:52
  • only TF_CPP_MIN_LOG_LEVEL worked for tensorflow-2.4.1 – banderlog013 May 26 '21 at 23:41
  • TF 2.9.1, `tf.logging` does not exist, `tf.get_logger().setLevel(...)` does not work. Only the method with the `os` environ var worked. – amzon-ex Oct 06 '22 at 21:46
  • `tf.get_logger().setLevel('ERROR')` worked for me. – J.J. Feb 05 '23 at 09:05
  • 1
    The table of messages is misleading. `0` should be labeled `INFO` since it displays all messages. (Apparently there are no `DEBUG` messages?). Likewise, `1` should be `WARNING` since it displays `WARNING` and `ERROR` messages but not `INFO` messages. Likewise, `3` should be `NONE` since it filters out all messages. – jordanbtucker Feb 10 '23 at 20:01
59

For compatibility with Tensorflow 2.0, you can use tf.get_logger

import logging
tf.get_logger().setLevel(logging.ERROR)
serv-inc
  • 35,772
  • 9
  • 166
  • 188
21

I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.

I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)
Pedro Lopes
  • 2,833
  • 1
  • 30
  • 36
  • 1
    Worked for me, while TF_CPP_MIN_LOG_LEVEL solution didn't. Good thinking! – fault-tolerant Mar 05 '18 at 05:50
  • Only solution that worked for me with tensorflow 1.12. – BiBi Jan 08 '19 at 12:00
  • Using `tensorflow-gpu 1.14.0`. Recieved this output when called the function above `The name tf.logging.set_verbosity is deprecated. Please use tf.compat.v1.logging.set_verbosity instead.` `WARNING:tensorflow:From C:/.../NN.py:297: The name tf.logging.ERROR is deprecated. Please use tf.compat.v1.logging.ERROR instead.` Pleasing that there were no no warnings after these messages – A.Ametov Oct 06 '19 at 23:52
17

I am using Tensorflow version 2.3.1 and none of the solutions above have been fully effective.
Until, I find this package.

Install like this:

with Anaconda,

python -m pip install silence-tensorflow

with IDEs,

pip install silence-tensorflow

And add to the first line of code:

from silence_tensorflow import silence_tensorflow
silence_tensorflow()

That's It!

oreitor
  • 171
  • 1
  • 4
  • 1
    This is the only thing that worked for me in this entire thread. Thanks! (I'm using Tensorflow 2.9.1) – mime Jun 24 '22 at 04:06
  • 3
    It's a sad thing a separate package `silence-tensorflow`is needed to suppress the tensorflow output. – Bart Oct 22 '22 at 07:27
16

To anyone still struggling to get the os.environ solution to work as I was, check that this is placed before you import tensorflow in your script, just like mwweb's answer:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf
12

I solved with this post Cannot remove all warnings #27045 , and the solution was:

import logging
logging.getLogger('tensorflow').disabled = True
Mandy007
  • 421
  • 7
  • 18
11

As TF_CPP_MIN_LOG_LEVEL didn't work for me you can try:

tf.logging.set_verbosity(tf.logging.WARN)

Worked for me in tensorflow v1.6.0

Wikunia
  • 1,564
  • 1
  • 16
  • 37
6

Usual python3 log manager works for me with tensorflow==1.11.0:

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)
estevo
  • 941
  • 11
  • 11
3

for tensorflow 2.1.0, following code works fine.

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
Baycosinus
  • 106
  • 7
2

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.

Tyler
  • 28,498
  • 11
  • 90
  • 106
2

Yeah, I'm using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don't seem to exist anymore.

I stepped around in PDB and found this to work:

# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])

I then add my own logger API (in this case file-based)

logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)

# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)
dturvene
  • 2,284
  • 1
  • 20
  • 18
2

Just run the silence_tensorflow function from silence-tensorflow package before importing tensorflow:

"""Module providing tools to shut up tensorflow useless warnings, letting you focus on the actual problems."""
import os
import logging


def silence_tensorflow():
    """Silence every unnecessary warning from tensorflow."""
    logging.getLogger('tensorflow').setLevel(logging.ERROR)
    os.environ["KMP_AFFINITY"] = "noverbose"
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    # We wrap this inside a try-except block
    # because we do not want to be the one package
    # that crashes when TensorFlow is not installed
    # when we are the only package that requires it
    # in a given Jupyter Notebook, such as when the
    # package import is simply copy-pasted.
    try:
        import tensorflow as tf
        tf.get_logger().setLevel('ERROR')
        tf.autograph.set_verbosity(3)
    except ModuleNotFoundError:
        pass

Disclaimer: I'm not the author of this package.

Teddy C
  • 786
  • 10
  • 13
1

I was struggling from this for a while, tried almost all the solutions here but could not get rid of debugging info in TF 1.14, I have tried following multiple solutions:

import os
import logging
import sys

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # FATAL
stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')

import tensorflow as tf
tf.get_logger().setLevel(tf.compat.v1.logging.FATAL)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
logging.getLogger('tensorflow').setLevel(tf.compat.v1.logging.FATAL)

sys.stderr = stderr

import absl.logging
logging.root.removeHandler(absl.logging._absl_handler)
absl.logging._warn_preinit_stderr = False

The debugging info still showed up, what finally helped was restarting my pc (actually restarting the kernel should work). So if somebody has similar problem, try restart kernel after you set your environment vars, simple but might not come in mind.

Ruli
  • 2,592
  • 12
  • 30
  • 40
1

In Jupyter notebooks, you can use the %env magic command:

%env TF_CPP_MIN_LOG_LEVEL=3
import tensorflow as tf
Matteo
  • 135
  • 2
  • 7
  • This was the best solution for me, with the goal of creating a simple demonstration notebook that should not be bloated with additional packages or code lines – dennis Jun 12 '23 at 14:40
0

If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience):

In windows:

import os
os.system('cls')

In Linux or Mac:

import os
os.system('clear')
Masoud Masoumi Moghadam
  • 1,094
  • 3
  • 23
  • 45
  • 1. No, isn't more effective. 2. Is a potential security risk. 3. You should never call system for such tasks. 4. There are far better ways to do this as explained in many answers here. – Lin Apr 26 '21 at 14:31
0

None of the solutions above could solve my problem in Jupyter Notebook, so I use the following snippet code bellow from Cicoria, and issues solved.

import warnings  
with warnings.catch_warnings():  
    warnings.filterwarnings("ignore",category=FutureWarning)
    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras.preprocessing.text import Tokenizer

print('Done') 
Erman
  • 1,543
  • 17
  • 26
0

Most of the answers here work, but you have to use them every time you open a new session (e.g. with JupyterLab). To make the changes stick, you have to set the environment variable.

Linux:

export TF_CPP_MIN_LOG_LEVEL="3"

(Also add the above line to .bashrc to make the change permanent, not just for the session)

Windows:

setx TF_CPP_MIN_LOG_LEVEL "3"

Both set the environment variables for the user.

Bex T.
  • 1,062
  • 1
  • 12
  • 28
0

After testing various suggestions so that they could also silence the resulting executable built with PyInstaller, I came up with this setting:

import logging
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
logging.getLogger('tensorflow').setLevel(logging.ERROR)

import tensorflow as tf

The line

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

will silent the warning about rebuilding TensorFlow:

I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA. To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

The line

logging.getLogger('tensorflow').setLevel(logging.ERROR)

will silent the warning about AutoGraph:

WARNING:tensorflow:AutoGraph is not available in this environment: functions lack code information. This is typical of some environments like the interactive Python shell. See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code for more information.

The key point is to place these two before importing Tensorflow—despite Pylint's warning!

tensorflow 2.11.0

Shahrokh Bah
  • 332
  • 3
  • 5
0

This one worked for me perfectly, to turn off all the loggs

import logging, os

logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

import tensorflow as tf
stanly
  • 63
  • 1
  • 6