Skip to content

Remove some side effects and add an optional to save log to file as well. #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,16 @@ that uses the standard Python logging module will play along nicely.
Behaviours
----------

- Messages are always written to stderr.
- Messages are always written to `stderr` if `glog` is used uninitialized.

- By calling `glog.init(FILE_NAME)`, where FILE_NAME is a `str`, logs will be
saved to that file. Target files only need to be initialized once and could
be shared anywhere. Repeated initialization is supported, and all logs will
be added to that file only once.

- Calling `glog.init("stderr")` or `glog.init("stdout")` will make glog log to
standard error or standard output.


- Lines are prefixed with a google-style log prefix, of the form

Expand Down Expand Up @@ -76,6 +85,19 @@ parsing flags, like so:
log.init()
main(posargs[1:])

To show log and save a copy to file at the same time:

.. code:: python

import glog as log

log.init("example.log")

log.info("It works.")
log.warn("Something not ideal")
log.error("Something went wrong")
log.fatal("AAAAAAAAAAAAAAA!")

Happy logging!

.. _twitter.common.log: https://github.com/twitter/commons/tree/master/src/python/twitter/common/log
Expand Down
64 changes: 44 additions & 20 deletions glog.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@
* Your apps and scripts will all have a consistent log format, and the same
predictable behaviours.

This library configures the root logger, so nearly everything you import
that uses the standard Python logging module will play along nicely.

## Behaviours

* Messages are always written to stderr.
* Messages are always written to `stderr` if `glog` is used uninitialized.

* By calling `glog.init(FILE_NAME)`, where FILE_NAME is a `str`, logs will be
saved to that file. Target files only need to be initialized once and could
be shared anywhere. Repeated initialization is supported, and all logs will
be added to that file only once.

* Calling `glog.init("stderr")` or `glog.init("stdout")` will make glog log to
standard error or standard output.

* Lines are prefixed with a google-style log prefix, of the form

Expand Down Expand Up @@ -64,6 +69,7 @@ def main():

Happy logging!
"""
import sys

import logging
import time
Expand All @@ -74,6 +80,8 @@ def main():
short_name='v')
FLAGS = gflags.FLAGS

file_names = []


def format_message(record):
try:
Expand Down Expand Up @@ -112,10 +120,7 @@ def format(self, record):
record.getMessage = lambda: record_message
return logging.Formatter.format(self, record)

logger = logging.getLogger()
handler = logging.StreamHandler()

level = logger.level
logger = logging.getLogger("glog")


def setLevel(newlevel):
Expand All @@ -124,17 +129,36 @@ def setLevel(newlevel):
logger.debug('Log level set to %s', newlevel)


def init():
def init(filename=None):
logger.propagate = False
if filename is None:
if "stderr" not in file_names:
handler = logging.StreamHandler()
filename = "stderr"
elif filename in file_names:
# Do not add files that already has been added.
return
elif filename == "stderr":
handler = logging.StreamHandler(sys.stderr)
elif filename == "stdout":
handler = logging.StreamHandler(sys.stdout)
else:
handler = logging.FileHandler(filename)

file_names.append(filename)
handler.setFormatter(GlogFormatter())
logger.addHandler(handler)
setLevel(FLAGS.verbosity)

debug = logging.debug
info = logging.info
warning = logging.warning
warn = logging.warning
error = logging.error
exception = logging.exception
fatal = logging.fatal
log = logging.log
debug = logger.debug
info = logger.info
warning = logger.warning
warn = logger.warning
error = logger.error
exception = logger.exception
fatal = logger.fatal
log = logger.log


DEBUG = logging.DEBUG
INFO = logging.INFO
Expand All @@ -143,6 +167,8 @@ def init():
ERROR = logging.ERROR
FATAL = logging.FATAL

# basicConfig = logger.basicConfig

_level_names = {
DEBUG: 'DEBUG',
INFO: 'INFO',
Expand All @@ -166,6 +192,4 @@ def init():
""") % ''.join(_level_letters)
"""Regex you can use to parse glog line prefixes."""

handler.setFormatter(GlogFormatter())
logger.addHandler(handler)
setLevel(FLAGS.verbosity)
init()