log.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ########################################################################
  4. #
  5. # Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ########################################################################
  8. """
  9. File: log.py
  10. Author: dongzihui(dongzihui@baidu.com)
  11. Date: 2015/05/17 21:09:24
  12. """
  13. import os
  14. import logging
  15. import logging.handlers
  16. def init_log(log_path, level=logging.INFO, when="D", backup=7,
  17. format="%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d %(message)s",
  18. datefmt="%m-%d %H:%M:%S"):
  19. """
  20. init_log - initialize log module
  21. Args:
  22. log_path - Log file path prefix.
  23. Log data will go to two files: log_path.log and log_path.log.wf
  24. Any non-exist parent directories will be created automatically
  25. level - msg above the level will be displayed
  26. DEBUG < INFO < WARNING < ERROR < CRITICAL
  27. the default value is logging.INFO
  28. when - how to split the log file by time interval
  29. 'S' : Seconds
  30. 'M' : Minutes
  31. 'H' : Hours
  32. 'D' : Days
  33. 'W' : Week day
  34. default value: 'D'
  35. format - format of the log
  36. default format:
  37. %(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
  38. INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
  39. backup - how many backup file to keep
  40. default value: 7
  41. Raises:
  42. OSError: fail to create log directories
  43. IOError: fail to open log file
  44. """
  45. formatter = logging.Formatter(format, datefmt)
  46. logger = logging.getLogger()
  47. logger.setLevel(level)
  48. dir = os.path.dirname(log_path)
  49. if not os.path.isdir(dir):
  50. os.makedirs(dir)
  51. handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log",
  52. when=when,
  53. backupCount=backup)
  54. handler.setLevel(level)
  55. handler.setFormatter(formatter)
  56. logger.addHandler(handler)
  57. handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log.wf",
  58. when=when,
  59. backupCount=backup)
  60. handler.setLevel(logging.WARNING)
  61. handler.setFormatter(formatter)
  62. logger.addHandler(handler)