Skip to content

Commit

Permalink
Merge pull request #4 from ansrivas/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
ansrivas authored Apr 12, 2018
2 parents b3c39b3 + 3ce8059 commit e4ef0a8
Show file tree
Hide file tree
Showing 8 changed files with 155 additions and 94 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,5 @@ ENV/

# mypy
.mypy_cache/

README.md
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include README.rst
75 changes: 0 additions & 75 deletions README.md

This file was deleted.

94 changes: 94 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
pylogging
~~~~~~~~~

A simple python logger which writes logs to disk with some default
configs.

Compatible with:
~~~~~~~~~~~~~~~~

Python 2.7 and 3.5

Current stable version:
~~~~~~~~~~~~~~~~~~~~~~~

::

0.2.3

Installation:
~~~~~~~~~~~~~

Install using pip
^^^^^^^^^^^^^^^^^

::

pip install git+https://github.com/ansrivas/pylogging.git --upgrade

Install by adding to requirements.txt of your project
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

- Add the following lines to your ``requirements.txt`` file.
``git+https://github.com/ansrivas/pylogging.git``

- Install all packages in your ``requirements.txt`` file by running the
command: ``$ pip install -r requirements.txt``

Install by adding to setup.py of your project
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

- Add the following to the ``install_requires`` parameter of your setup
function: ``install_requires=['pylogging==0.1.0'],``

- Add the following to the ``dependency_links`` parameter of your setup
function:
``dependency_links=['https://github.com/ansrivas/pylogging/tarball/master#egg=pylogging-0.1.0'],``

- Install your project along with ``pylogging`` by running the command:
``python setup.py install``

Usage:
~~~~~~

- ``setup_logger`` sets up the global logger with the provided
settings. After calling it once, simply ``import logging`` and create
a logger for that module ``logger = logging.getLogger(__name__)`` and
use it at shown below.

::

from pylogging import HandlerType, setup_logger
import logging

logger = logging.getLogger(__name__)

if __name__ == '__main__':
setup_logger(log_directory='./logs', file_handler_type=HandlerType.ROTATING_FILE_HANDLER, allow_console_logging=True)

logger.error("Error logs")
logger.debug("Debug logs")
logger.info("Info logs")

Important arguments to ``setup_logger`` function:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

log_directory (str) :directory to write log files to. Applicable only when `allow_file_logging` = True
file_handler_type :object of logging handler from HandlerType class. Applicable only when `allow_file_logging` = True
allow_console_logging (bool) :Turn off/on the console logging.
allow_file_logging (bool) :Turn off/on if logs need to go in files as well.
backup_count (int) :Number of files to backup before rotating the logs.
max_file_size_bytes (int) :Size of file in bytes before rotating the file. Applicable only to ROTATING_FILE_HANDLER.
when_to_rotate (str) :Duration after which a file can be rotated. Applicable only to TIME_ROTATING_FILE_HANDLER
Accepts following values:
'S' Seconds
'M' Minutes
'H' Hours
'D' Days
'W0'-'W6' Weekday (0=Monday)
'midnight' Roll over at midnight
change_log_level (dict) :A dictionary of handlers with corresponding log-level ( for eg. {'requests':'warning'} )
console_log_level (dict) :Change the LogLevel of console log handler, default is INFO
gelf_handler :An external handler for graylog data publishing.
6 changes: 3 additions & 3 deletions pylogging/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Initialize module utils."""

from .create_logger import setup_logger
__all__ = ['setup_logger', 'HandlerType', 'Formatters']
from ._create_logger import setup_logger
from .handler_types import HandlerType
from .formatters import Formatters

__version__ = '0.2.0'
__version__ = '0.2.3'
31 changes: 18 additions & 13 deletions pylogging/create_logger.py → pylogging/_create_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,26 @@
# -*- coding: utf-8 -*-
"""Docstring for logging module."""

import os
import logging
import logging.handlers
import os

from future.utils import raise_with_traceback as rwt
from future.utils import iteritems

from pylogging.handler_types import HandlerType
from pylogging.log_levels import LogLevel
from pylogging.formatters import Formatters
from pylogging.handler_types import HandlerType

from future.utils import iteritems
from future.utils import raise_with_traceback as rwt


def __set_log_levels(level_dict):
"""Set the log levels for any log-handler for e.g. level_dict = {'requests':'error'}."""
if not isinstance(level_dict, dict):
rwt(TypeError('Expecting dict object with format: \{\'requests\':\'warning\'\} \n' +
rwt(TypeError('Expecting dict object with format: \{\'requests\':\'warning\'\} \n'
'Available levels are: {0}'.format(LogLevel.levels.keys)))
else:
for key, val in iteritems(level_dict):
logging.getLogger(key).setLevel(LogLevel.get_level(val))

for key, val in iteritems(level_dict):
logging.getLogger(key).setLevel(LogLevel.get_level(val))


def __setup_file_logging(g_logger=None,
Expand All @@ -35,6 +35,7 @@ def __setup_file_logging(g_logger=None,
generated_files = os.path.join(os.path.abspath(os.path.expanduser(log_directory)))
if not os.path.exists(generated_files):
os.makedirs(generated_files)

all_logs_fname = '{0}/all.log'.format(generated_files)
error_logs_fname = '{0}/error.log'.format(generated_files)

Expand Down Expand Up @@ -78,7 +79,8 @@ def setup_logger(log_directory='.',
when_to_rotate='D',
change_log_level=None,
log_formatter=Formatters.TextFormatter,
gelf_handler=None):
gelf_handler=None,
**kwargs):
"""Set up the global logging settings.
Args:
Expand All @@ -97,16 +99,18 @@ def setup_logger(log_directory='.',
'W0'-'W6' Weekday (0=Monday)
'midnight' Roll over at midnight
change_log_level (dict) :A dictionary of handlers with corresponding log-level ( for eg. {'requests':'warning'} )
console_log_level (logging) :Change the LogLevel of console log handler, default is logging.INFO (e.g. logging.DEBUG, logging.INFO)
gelf_handler :An external handler for graylog data publishing.
"""
if file_handler_type not in [HandlerType.ROTATING_FILE_HANDLER,
HandlerType.TIME_ROTATING_FILE_HANDLER]:
file_handlers = [HandlerType.ROTATING_FILE_HANDLER, HandlerType.TIME_ROTATING_FILE_HANDLER]
if file_handler_type not in file_handlers:
rwt(ValueError('Please pass an object of HandlerType class'))

if change_log_level:
__set_log_levels(change_log_level)

logger = logging.getLogger()
logger.propagate = False
logger.setLevel(logging.DEBUG)

if gelf_handler:
Expand All @@ -115,7 +119,8 @@ def setup_logger(log_directory='.',
# create console handler and set level to info
if allow_console_logging:
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
log_level = kwargs.get("console_log_level", logging.INFO)
handler.setLevel(log_level)
handler.setFormatter(log_formatter)
logger.addHandler(handler)

Expand Down
Empty file added setup.cfg
Empty file.
40 changes: 37 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,46 @@
import re
from os import path

from codecs import open # To use a consistent encoding
from setuptools import find_packages, setup

here = path.abspath(path.dirname(__file__))

# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()


def get_version():
with open('pylogging/__init__.py') as version_file:
return re.search(r"""__version__\s+=\s+(['"])(?P<version>.+?)\1""",
version_file.read()).group('version')


setup(name='pylogging',
version='0.2.0',
version=get_version(),
description='File logging for Python',
long_description=long_description,
author='Ankur Srivastava',
author_email='[email protected]',
url='https://github.com/ansrivas/pylogging',
download_url='https://github.com/ansrivas/pylogging/tarball/0.2.0',
download_url='https://github.com/ansrivas/pylogging/tarball/{0}'.format(get_version()),
include_package_data=True,
license='MIT',
install_requires=['future', 'requests', 'requests-futures', 'ujson', 'graypy'],
zip_safe=False,
install_requires=['future', 'requests-futures', 'ujson', 'graypy'],
extras_require={
'dev': [
'pytest',
'pytest-pep8',
'pytest-cov',
]
},
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6", ],
packages=find_packages())

0 comments on commit e4ef0a8

Please sign in to comment.