Saravanan666/pypi-org huggingface dataset:
Package: logging-reporter
Lightweight logger decorators for pythonLicense:MITWhat is this repository?Extends default python loggingmoduleto make it easier to log actions before and after running functions and methods.
Usefull when debugging an application and you want to see the time a function takes or when the function was called.FeaturesDisplay when a function was executedDisplay the result of a functionDisplay a value before and after a fucntion was executedDisplay the execution timeDisplay thestrandreprmethod of an object before and afterHow do I get set up?Usepip install git+ssh://git@github.com/2019342a/reporterto install the library. Then you are good to go!Dependencieslogging-reporter requirescolorlogto add colour to the reporter logs.Examplefromreporter.utilsimportcreate_reporterfromreporter.decoratorsimportreport_execution# Initialise the loggercreate_reporter()@report_executiondefadd(a:int,b:int)->int:returna+badd(1,2)You should then see in your terminal something like:2021-05-15 11:05:53,114 - reporter - DEBUG - add was executed with args 1 2ContactIf you have any questions, bugs or features please open a github issue.
Package: logging-singleton
Singleton Logging ServiceLogging service that is guaranteed to be a singleton. Based on Python logging, but every instantiation of LoggingService from any of an application's modules returns the same logger instance.###Examples:from logging_service import LoggingService

    self.log = LoggingService()

    self.log.info("Constructing output file names...")
    self.log.err("Failed to construct output file names...")
    self.log.warn("Output file names are unusual...")
    self.log.debug("Constructing output file names foo.bar, fum.txt...")This API is more primitive than the hierarchical native logging module, but hopefully simple to use. One can:- Log to a file,
    - The console, or
    - BothA single formatter is built in for info/debug/warn/err. Example:my_module.py(290375): 2020-09-03 14:58:33,017;INFO: Start Epoch [1/50]When first creating a LoggingService instance, the following options
are available in the constructor; all are optional:logging_level=logging.INFO    # the Python logging package's constants
logfile=None,                 # destination file; None implies console only
tee_to_console=True,          # if logfile is specified, also log to console
msg_identifier=None,          # shown at start of each msg; default is module name
rotating_logs=True,           # if logging to file, rotate log if size exceeded
log_size=1000000,             # max log size for rotation
max_num_logs=500,             # max number of full logs to retain
logger_name=None              # name for the logger instanceAfter creation a logger instance may only be modified like this:- my_logger.logging_level = logging.NEW_LEVEL
- my_logger.log_file      = '/tmp/new_logfile'where logging levels are the usuallogging.INFO,logging.WARN, etc.
Package: logging-slacker
logging_slackerPython log handler that posts to a Slack channel. Posts to the Slack API
usingPython Slack SDK.Related Repos:Mathias Ose:slacker_log_handlerlog-to-slackpython-slack-loggerInstallationpipinstalllogging_slackerArgumentsslack_token (str): The Slack API token if not usingwebhook_urlGenerate a key athttps://api.slack.com/channel (str): The Slack channel to post to if not usingwebhook_urlwebhook_url (str): The Slack webhook URL if usingwebhook_urlis_webhook (bool): Whether to use webhook_url or not (Defaults toTrue)is_debug (bool): Doesn't send Slack messages if True (Defaults toFalse)stack_trace (bool): Whether to include the stacktrace in the Slack message (Defaults toTrue)username (str): The username to use for the Slack message (Not usable if usingwebhook_url)icon_url (str): The icon URL to use for the Slack message (Not usable if usingwebhook_url)icon_emoji (str): The icon emoji to use for the Slack message (Not usable if usingwebhook_url)msg_len (int): The maximum length of the Slack message (Defaults to1300)traceback_len (int): The maximum length of the stack_trace (Defaults to700)fail_silent (bool): Whether to fail silently if the Slack API returns an error (Defaults toFalse)
Defaults toFalse. If your API key is invalid or for some other reason
the API call returns an error, this option will silently ignore the API
error. If you enable this setting,make sure you have another log
handlerthat will also handle the same log events, or they may be lost
entirely.Example Python logging handlerThis is how you use log_to_slack as a regular Python
logging handler. This example will send a error message to a slack
channel.importloggingimportosfromlog_to_slackimportSlackLogHandlerfromlog_to_slack.formattersimportNoStacktraceFormatter,DefaultFormatterWEBHOOK_URL=os.getenv("WEBHOOK_URL")logger=logging.getLogger("debug_application")logger.setLevel(logging.DEBUG)default_formatter=DefaultFormatter("%(levelprefix)s%(asctime)s(%(name)s)%(message)s")no_stacktrace_formatter=NoStacktraceFormatter("%(levelprefix)s%(asctime)s(%(name)s)%(message)s")default_handler=logging.StreamHandler()default_handler.setFormatter(default_formatter)logger.addHandler(default_handler)slack_handler=SlackLogHandler(webhook_url=WEBHOOK_URL,stack_trace=True)slack_handler.setFormatter(no_stacktrace_formatter)slack_handler.setLevel(logging.ERROR)logger.addHandler(slack_handler)# Main codelogger.debug("Test DEBUG")logger.info("Test INFO")logger.warning("Test WARNING")logger.error("Test ERROR")logger.fatal("Test FATAL")logger.critical("Test CRITICAL")try:raiseException("Test exception")exceptExceptionase:logger.exception(e)Slack message formattingThis example use a subclass that will send a formatted message to a
Slack channel.Learn MoreclassCustomLogHandler(SlackLogHandler):defbuild_msg(self,record):message="> New message :\n"+record.getMessage()returnmessageLicenseApache 2.0See also:https://api.slack.com/terms-of-service
Package: logging-spinner
This library helps to display loading spinners in CLI in non-intrusive manner.
Applications/libraries don’t have to depend on any third-party API, but only
need to log loading messages through Python’s standardlogginglibrary:logger=logging.getLogger('myapp.logger')logger.info('Loading data...',extra={'user_waiting':True})# some long taking process goes here...logger.info('Finished loading!',extra={'user_waiting':False})At the outest code of the application, setup aSpinnerHandler:fromlogging_spinnerimportSpinnerHandlerlogger=logging.getLogger('myapp')logger.setLevel(logging.INFO)logger.addHandler(SpinnerHandler())SpinnerHandleris only aware of log records withuser_waitingextra
field and displays them with a spinner.See alsosample.pycode.Author and licenseWritten byHong Minheeand distributed underGPLv3or later.ChangelogVersion 0.2.2Released on June 22, 2017.Fixed aValueErrorraised when a log record with{'user_waiting': Flase}is made without any previous log records
with{'user_waiting': True}.Version 0.2.1Released on May 21, 2017.Fixed a bug thatSpinerHandlerhad crashed whenuser_waitinglog
records show a spinner again after a previous spinner was hidden.Version 0.2.0Released on May 21, 2017.logging_spinner.UserWaitingFilterwas introduced to avoid duplicate
prints of a log record withuser_waitingextra field.Version 0.1.0Released on May 21, 2017.  The initial release.
Package: logging-timehandler
Log files are generated based on the time and the latest n logs are automatically retainedExampleimportloggingimportlogging_timehandlerlogger=logging.getLogger(__name__)handler=logging_timehandler.TimeHandler('./log/%Y_%m_%d/%Y_%m_%d_%S.txt',retain=5)handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))logger.addHandler(handler)logger.setLevel(logging.INFO)foriinrange(10):logger.info('hello')
Package: logging-toolbox
logging-toolboxThelogging-toolboxmodule contains useful functions to help the user
with logging recurring things like command-line arguments and dependencies
on startup.UsageLogging program arguments and dependenciesSuppose we have a Python program that has the dependenciesdep1anddep2,
and takes the command-line arguments--server-url,--one-argumentand--some-hex-value. We'll assume the module the program is a part of is
calledsimple_program. Upon startup, we can log the versions of our
dependencies and all arguments.from.utilsimportget_args,setup_loggingfromlogging_toolbox.startupimportstartup_logfromlogging_toolbox.utilsimportclean_urlif__name__=='__main__':arguments=get_args()setup_logging()startup_log(arguments,critical_modules=['simple_program','dep1','dep2'],cleaners={'server_url':clean_url,'some_hex_value':'0x{:04X}'.format})This should log something like:=================CONFIG=================
----------------Versions----------------
simple_program : UNKNOWN
dep1           : 0.3.2.dev23
dep2           : 1.0.1
---------------Arguments----------------
one_argument   : argument value
server_url     : https://user:******@server/
some_hex_value : 0x02FF
=======================================
Package: loggingtools
Python Tools for Setting up LoggingLoggingtoolssetup_loggingimportloggingfromloggingtoolsimportsetup_loggingsetup_logging('logging.yml')logger=logging.getLogger('<your_logger>')...log_withimportloggingfromloggingtoolsimportlog_with...# setup your loggerslogger=logging.getLogger('<your_logger>')@log_with(logger)deffunction(arg,arg2):...InstallationLoggingtools can be installed throughpipusing commandpipinstallloggingtoolsCommand Line Clientloggingtools configCommand line arguments-n,--filename=loggingFilename for logging configuration-f,--fileformat=ymlFileformat: {yml, json}Referenceshttps://docs.python.org/3/library/logging.htmlhttps://github.com/borntyping/python-colorlog
Package: logging-tz
Python 2 logging module doesn’t support using a timezone offset%zin the datetime format string.  An example failure mode is shown below:importloggingdatefmt='%Y-%m-%d%H:%M:%S%z'logging.basicConfig(format='%(asctime)s%(message)s',datefmt=datefmt)logging.warning("Dude, where's my tzinfo?")# it's about 6.20 pm here in Chicago# 2017-02-27 18:23:05+0000 Dude, where's my tzinfo?^^^^^Simply omitting the time zone offset would perhaps have been admissible, or perhaps even simply refusing to localize and just logging in UTC, but specifying the localized timeandspecifying a zero offset is certainly wrong.  The part marked^is incorrect, an offset timestamp should have looked more like this one:importpytzfromdatetimeimportdatetimechicago_now=datetime.now(tz=pytz.timezone('America/Chicago'))printchicago_now.strftime(datefmt)# 2017-02-27 18:23:13-0600Indeed, that’s how the logging outputdoeslook if run under Python 3.  But in Python 2, the%zdirective is dropped.  This module provides aLocalFormatterintended as a drop-in replacement, to provide the correct handling of time zone offsets under Python 2:importlogging,logging_tzdatefmt='%Y-%m-%d%H:%M:%S%z'logger=logging.getLogger('wat')handler=logging.StreamHandler()formatter=logging_tz.LocalFormatter(fmt='%(asctime)s%(message)s',datefmt=datefmt)handler.setFormatter(formatter)logger.addHandler(handler)logger.warning("Ah, there's my tzinfo!")# 2017-02-27 18:25:53-0600 Ah, there's my tzinfo!Additionally aChicagoFormatteris offered as a convenience, to ease the pain for anyone insane enough to run their backend on CST instead of UTC.FAQQ:How to install this library?A:pip install logging_tzand then you can just use alogging_tz.LocalFormatterinstead of thelogging.Formatter.Q:You should log in UTC.  Why would you log in local time anyway?A:Yeah, I guess.  Although handling the date format correctly is at least better than mucking it up completely.Q:Is that a bug in Python?A:Hmm, arguably not, because the%zdirective for time zone offset is not listed on thetime.strftimetable in thePython 2 documentation.  It isthere in the Python 3 docs, though.Q:Did people really ask you these questions?  I bet you just made them up for the FAQ.A:That’s a very good question - it’s one I’ve frequently asked myself, in fact.
Package: logging_unterpolation
logging_unterpolation is a very simple module that will patch the built-in logging module to accept PEP-3101 compliant string formatting (using the str.format method) as well as falling back to accept the original string interpolation operator (% or ‘modulo’)Here’s a basic example:>>> import logging
>>> from logging_unterpolation import patch_logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.debug('test')
DEBUG:root:test
>>> logging.debug('%s', 'test') # example of built-in string interpolation in log messages
DEBUG:root:test
>>> patch_logging()
>>> logging.debug('{0}', 'test') # format syntax not supported unless patched
DEBUG:root:test
Package: logging-utils-tddschn
logging-utils-tddschnLogging utilities for personal use.logging-utils-tddschnInstallExample Usageget_loggerInstall$ pip install logging-utils-tddschnExample Usageget_loggerCheck the source code linked above to learn more about the arguments.fromlogging_utils_tddschnimportget_loggerlogger,_=get_logger(__name__)logger.info('Logging from logging-utils-tddschn!')_DEBUG=1 python3 app.py
# prints something like
# INFO:tests.test_utils_naive:/Users/tddschn/app.py:5:my_func:Logging from logging-utils-tddschn!

# logging is turned off (sent to NullHandler) if you don't set env var _DEBUG or it's set to false.
Package: loggingx
loggingxlogging拓展功能模块。Installation|UsageInstallation安装loggingx，只需要执行：pipinstallloggingxloggingx部分功能需要依赖消息队列，需要安装相关依赖，可以通过以下命令安装必要的依赖：pipinstall"loggingx[queue]"Usageloggingx在使用上基本和logging一致。handlers.RedisStreamHandler将日志消息发布到redis stream消息队列，配合handlers.RedisStreamListener可以解决多进程写日志文件不安全的问题。# 示例一：直接使用logger=logging.getLogger('test')logger.setLevel(logging.DEBUG)rsh=RedisStreamHandler('redis://redis:6379/0')logger.addHandler(rsh)# 示例二：在配置文件中使用LOGGING_CONFIG={'version':1,'disable_existing_loggers':False,'formatters':{'verbose':{'format':'%(asctime)s.%(msecs)03d%(levelname)-8s%(processName)s:%(threadName)s%(pathname)s:%(lineno)d-%(message)s','datefmt':'%Y-%m-%d%H:%M:%S'},'simple':{'format':'{name:s}:{asctime:s}{levelname}{message}','style':'{','datefmt':'%Y-%m-%d%H:%M:%S'},},'handlers':{'console':{'class':'logging.StreamHandler','level':'INFO','formatter':'simple'},'redis_stream':{'class':'loggingx.handlers.RedisStreamHandler','level':'INFO','redis_url':'redis://redis:6379/0'}},'loggers':{'cloud':{'handlers':['console'],'propagate':True,},'cloud.request':{'handlers':['redis_stream'],'level':'INFO','propagate':True,}},}logging.config.dictConfig(LOGGING_CONFIG)在多进程服务中使用RedisStreamHandler，然后单独启动一个进程运行RedisStreamListener，可以保证日志消息完整传递到下游处理器。完整示例可以参考examples。handlers.RedisStreamListener消费redis stream消息队列的日志消息，传递到下游handlers。RedisStreamListener不属于处理器，需要和handlers.RedisStreamHandler配合工作。# 创建TimedRotatingFileHandler实例fh=logging.handlers.TimedRotatingFileHandler('logs/cloud.log',when='M',backupCount=5)fh.setLevel(logging.DEBUG)formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')fh.setFormatter(formatter)# 使用RedisStreamListener消费RedisStreamHandler消息，传递到TimedRotatingFileHandlerrsl=RedisStreamListener('redis://redis:6379/0',fh)rsl.start()
Package: loggingx-py
loggingx.pyloggingxis a drop-in replacement for Python's built-inloggingmodule. Even better, once you've importedloggingx, you don't need to modify your existingloggingmodule.python3-mpipinstallloggingx-pyAdditional Formathttps://docs.python.org/3/library/logging.html#logrecord-attributesAttribute nameFormatDescriptioncaller%(caller)sCaller(<pathname>:<lineno>)ctxFields%(ctxFields)sContext fieldsOptimizationConfigurationDescriptionlogging.logThreadsIfFalse, Record will not collectthreadandthreadName.logging.logProcessesIfFalse, Record will not collectprocess.logging.logMultiprocessingIfFalse, Record will not collectprocessName.Contextimportloggingxaslogginglogging.basicConfig(level=logging.INFO,format="%(asctime)s\t%(levelname)s\t%(caller)s\t%(message)s\t%(ctxFields)s",)defA()->None:logging.info("A")withlogging.addFields(A="a"):B()defB()->None:logging.info("B")withlogging.addFields(B="b"):C()defC()->None:logging.info("C")if__name__=="__main__":A()2023-07-1901:15:33,981INFOloggingx.py/main.py:10A{}2023-07-1901:15:33,981INFOloggingx.py/main.py:16B{'A':'a'}2023-07-1901:15:33,982INFOloggingx.py/main.py:22C{'A':'a','B':'b'}JSONFormatterimportloggingxaslogginghandler=logging.StreamHandler()# handler.setFormatter(logging.JSONFormatter())handler.setFormatter(logging.JSONFormatter(logging.Information.THREAD_NAME))logging.basicConfig(level=logging.INFO,handlers=[handler])if__name__=="__main__":withlogging.addFields(ctx="ctx"):logging.info("test",extra={"extra":"extra"}){"time":1689697694.9980711,"level":"info","caller":"loggingx.py/main.py:10","msg":"test","ctx":"ctx","thread_name":"MainThread","extra":"extra"}Withloggingimportloggingimportloggingx# handler = loggingx.StreamHandler()handler=logging.StreamHandler()handler.setFormatter(loggingx.JSONFormatter())# loggingx.basicConfig(level=loggingx.INFO, handlers=[handler])logging.basicConfig(level=logging.INFO,handlers=[handler])if__name__=="__main__":withloggingx.addFields(ctx="ctx"):# loggingx.info("test", extra={"extra": "extra"})logging.info("test",extra={"extra":"extra"})jqaliaslog2jq="jq -R -r '. as \$line | try fromjson catch \$line'"python3<path>2>&1|log2jq
Package: logglyproxy
This is a syslog server proxy.
The messages it receives are forwarded toLogglyvia HTTPS.
The server uses gevent and keep-alive http sessions for performance.Usage:logglyproxy -c config_fileHere’s an example config file:[logglyproxy]
bind_address = 127.0.0.1
port = 5140
apikey = xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxAnd an LSB init script:#! /bin/sh
### BEGIN INIT INFO
# Provides:          logglyproxy
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     false
# Short-Description: Start/stop logglyproxy

DAEMON="logglyproxy"
DAEMON_USR=logglyproxy
DAEMON_GRP=logglyproxy
INSTALLPATH=/path/to/logglyproxy/virtualenv
PIDFILE=/var/run/logglyproxy.pid

. /lib/lsb/init-functions

case "$1" in
  start)
    log_begin_msg "Starting logglyproxy server..."

    # Activate the virtual environment
    . $INSTALLPATH/bin/activate

    start-stop-daemon --background --make-pidfile \
        --start --pidfile $PIDFILE \
        --user $DAEMON_USR --group $DAEMIN_GRP \
        --chuid $DAEMON_USR \
        --exec "$INSTALLPATH/bin/$DAEMON"  -- -c /etc/logglyproxy.cfg
    log_end_msg $?
    ;;
  stop)
    log_begin_msg "Stopping logglyproxy server..."
    start-stop-daemon --stop --pidfile $PIDFILE --verbose
    log_end_msg $?
    ;;
  *)
    log_success_msg "Usage: /etc/init.d/logglyproxy {start|stop}"
    exit 1
    ;;
esac

exit 01.0 (01/02/2011)Initial release.
Package: loggly-python-handler
Python Logging Loggly HandlerA simple Python logging Loggly handler that can be used to send to a Loggly Gen2 https endpoint. Borrowed the extra fields concept from the graypy logging library. Check out Loggly'sPython logging documentationto learn more.InstallationDownload the repository using pipsudo pip install loggly-python-handlerUse in pythonConfigurationCreate a Configuration file python.conf and add HTTPSHandler to Configuration File.[handlers]
keys=HTTPSHandler

[handler_HTTPSHandler]
class=loggly.handlers.HTTPSHandler
formatter=jsonFormat
args=('https://logs-01.loggly.com/inputs/TOKEN/tag/python','POST')

[formatters]
keys=jsonFormat

[loggers]
keys=root

[logger_root]
handlers=HTTPSHandler
level=INFO

[formatter_jsonFormat]
format={ "loggerName":"%(name)s", "asciTime":"%(asctime)s", "fileName":"%(filename)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}
datefmt=Use Configuration in python fileimport logging
import logging.config
import loggly.handlers

logging.config.fileConfig('python.conf')
logger = logging.getLogger('myLogger')

logger.info('Test log')Use in Djangosettings.pyLOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
        'json': {
            'format': '{ "loggerName":"%(name)s", "asciTime":"%(asctime)s", "fileName":"%(filename)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'verbose',
        },
        'loggly': {
            'class': 'loggly.handlers.HTTPSHandler',
            'level': 'INFO',
            'formatter': 'json',
            'url': 'https://logs-01.loggly.com/inputs/TOKEN/tag/python',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console', ],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
        'your_app_name': {
            'handlers': ['console', 'loggly'],
            'level': 'INFO',
        },
    },
}views.pyimport logging

logger = logging.getLogger(__name__)

def logging_example(request):
    """logging example
    """
    logger.debug('this is DEBUG message.')
    logger.info('this is INFO message.')
    logger.warning('this is WARNING message.')
    logger.error('this is ERROR message.')
    logger.critical('this is CRITICAL message.')

    return Response({}, status=status.HTTP_200_OK)ReplaceTOKEN:your Loggly Customer Token
Package: loggly-search
loggly-searchA CLI for Loggly searchInstallationpip install loggly-searchConfigurationYou'll need both your account subdomain (ex.myaccountofmyaccount.loggly.com)
and anAPI tokento use this tool.
Both of these can then be passed via the--subdomainand--tokenparameters or
through theLOGGLY_SUBDOMAINandLOGGLY_TOKENenvironment variables.loggly-search --subdomain myaccount --token abcxyzUsage Examplesloggly-search --from=-7d CRITERIAloggly-search --from '2022-05-17T08:00:00.000-04:00' --to '2022-05-17T10:00:00.000-04:00' CRITERIA
Package: loggr
A simple Python logging handler which transmits logs to a centralized service
(also provided) with minimal work from both the web server side and the Python
side as well. For help, install the package, run loggr.py, and visit
localhost:8888 for more information.In the most basic form, simply add another handler to your existing logging
class via:import logging
from loggr import LoggrHandler

handler = LoggrHandler(url='http://someurl/', logname='optional-name')
logger = logging.getLogger('root')
logger.addHandler(handler)