daily pastebin goal
77%
SHARE
TWEET

logging_capture_warnings

a guest Aug 10th, 2018 133 in 22 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import logging
  2. import warnings
  3.  
  4.  
  5. def simple_format_warning(message, category, *args, **kwargs):
  6.     return '%s: %s' % (category.__name__, str(message))
  7.  
  8.  
  9. warnings.formatwarning = simple_format_warning
  10.  
  11.  
  12. logging.basicConfig(
  13.     filename="temp.log",
  14.     format=(
  15.         "%(asctime)s:%(msecs)-0.3f - %(levelname)s"
  16.         " - %(name)s - %(module)s:%(lineno)d"
  17.         " :: %(message)s"
  18.     ),
  19.     datefmt="%Y-%m-%d_%H:%M:%S",
  20. )
  21.  
  22. logger = logging.getLogger(__name__)
  23. logger.propagate = False
  24.  
  25.  
  26. formatter = logging.Formatter(
  27.     fmt=(
  28.         "%(asctime)s:%(msecs)-0.3f - %(levelname)s"
  29.         " - %(name)s - %(module)s:%(lineno)d"
  30.         " :: %(message)s"
  31.     ),
  32.     datefmt="%Y-%m-%d_%H:%M:%S",
  33.     style="%"
  34. )
  35. handler = logging.FileHandler(filename="temp.log")
  36. handler.setFormatter(formatter)
  37. logger.addHandler(handler)
  38.  
  39.  
  40. logging.captureWarnings(True)
  41.  
  42. warnings.warn("Warning message !!!")
  43. logger.warning("Logging message !!!")
  44.  
  45.  
  46. """
  47. In 'temp.log', I get these two lines :
  48. 2018-08-10_19:47:46:107.400 - WARNING - py.warnings - warnings:99 :: UserWarning: Warning message !!!
  49. 2018-08-10_19:47:46:108.400 - WARNING - __main__ - bug_capture_warning:43 :: Logging message !!!
  50.  
  51. If we look at the first line of log, we see 'warnings:99'
  52. but in my opinion it should be 'temp_code:42'
  53. """
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top