Saravanan666/pypi-org huggingface dataset:
Package: django-log-formatter-json
The library helps you to store logs in JSON format. Why is it important?
Well, it facilitates integration withLogstash.Usage example:importloggingimportjson_log_formatterformatter=json_log_formatter.JSONFormatter()json_handler=logging.FileHandler(filename='/var/log/my-log.json')json_handler.setFormatter(formatter)logger=logging.getLogger('my_json')logger.addHandler(json_handler)logger.setLevel(logging.INFO)logger.info('Sign up',extra={'referral_code':'52d6ce'})The log file will contain the following log record (inline).{"message":"Sign up","time":"2015-09-01T06:06:26.524448","referral_code":"52d6ce"}JSON librariesYou can useujsonorsimplejsoninstead of built-injsonlibrary.
They are faster and can serializeDecimalvalues.importjson_log_formatterimportujsonformatter=json_log_formatter.JSONFormatter()formatter.json_lib=ujsonDjango integrationHere is an example of how the JSON formatter can be used with Django.LOGGING['formatters']['json']={'()':'json_log_formatter.JSONFormatter',}LOGGING['handlers']['json_file']={'level':'INFO','class':'logging.FileHandler','filename':'/var/log/my-log.json','formatter':'json',}LOGGING['loggers']['my_json']={'handlers':['json_file'],'level':'INFO',}Let’s try to log something.importlogginglogger=logging.getLogger('my_json')logger.info('Sign up',extra={'referral_code':'52d6ce'})Custom formatterYou will likely need a custom log format. For instance, you want to log
a user ID, an IP address andtimeasdjango.utils.timezone.now().
To do so you should overrideJSONFormatter.json_record().classCustomisedJSONFormatter(json_log_formatter.JSONFormatter):defjson_record(self,message,extra,record):extra['message']=messageextra['user_id']=current_user_id()extra['ip']=current_ip()if'time'notinextra:extra['time']=django.utils.timezone.now()returnextraLet’s say you wantdatetimeto be serialized as timestamp.
Then you should useujson(which does it by default) and disable
ISO8601 date mutation.classCustomisedJSONFormatter(json_log_formatter.JSONFormatter):json_lib=ujsondefmutate_json_record(self,json_record):returnjson_recordTests$pipinstall-rrequirements.txt$tox
Package: django-loggable
this library adds ‘created_at’, ‘updated_at’ and ‘delete_at’ fields like
a rail apps in django, also added soft delete method.installpip install django-loggableHow to start1.- Add to django-loggable in the django apps:INSTALLED_APPS = [
    'django.contrib.admin',
  'django.contrib.auth',
        ...
  'django-loggable'
  ...
]2.- Extends LoggableModel in the model to use:class MyModel(LoggeableModel):
    field = models.CharField(max_length=20)3.- Add to django-admin:class ContactAdmin(LoggeableAdmin):
    pass
  ...
admin.site.register(Contact, ContactAdmin)
Package: django-loggable-util
Django loggable utilAn utility to create logs for request and response while keeping business code clean for class based views.MotivationBy using generic view, we can write a view as concise as this:classSomeModelCreateView(LoginRequiredMixin,CreateView):model=SomeModelAs we can see there is no place where we can writelogger.info(...). It won't be pretty to override some methods in the view just for printing logs.
It would make sense if there is already some overridden method in the view, then we could've put the logger
method there. That's why this package is created to quickly enable request and response logs for class based views.Installationpipinstalldjang-loggable-utilExample usageImport theLoggableclass in your urls.pyfromdjango_loggable_utilimportLoggableNow write url configuration as this:urlpatterns=[...path('someurl',Loggable(SomeCBView).as_view(),name='some-url-name'),...]You can pass usual parameters liketemplate_nameetc, inas_view()function.This will result in logs like this for every request response cycle:INFO | 2020-08-17 09:10:12.764 | {'request': {'method': 'GET', 'path': '/someurl', 'username': 'someuser', 'params': <QueryDict: {'somekey':'someval'}>}}
INFO | 2020-08-17 09:10:12.777 | {'response': {'username': 'someuser', 'status_code': 200, 'template': ['sometemplate.html']}}A default configuration is embedded with this package:default_log_config={'version':1,'disable_existing_loggers':False,'formatters':{'request_response_formatter':{'format':'%(levelname)s|%(asctime)s.%(msecs)03d|%(message)s','datefmt':"%Y-%m-%d%H:%M:%S",}},'handlers':{'request_response_console':{'level':'INFO','class':'logging.StreamHandler','formatter':'request_response_formatter'}},'loggers':{'request_response':{'handlers':['request_response_console'],'level':'INFO','propagate':False}}}This configuration streams logs to console. When it is needed to stream logs to files or any other service,
you can add that logging configuration insettings.pyand provide logger name to use for this library like this:LOGGABLE_LOGGER='your_logger_name'TodosWrite TestsSupport DRFSupport FBVLicenseMITFree Software, Hell Yeah!
Package: django_logger
Пакет django_logger предназначен для хранения и периодической записи логов в базу данных.Чтобы начать использовать django_logger нужно:1) создать модель для храниения логов:class Log(models.Model):level = models.CharField(max_length=200)message = models.TextField()extra = models.TextField()created_at = models.DateTimeField(auto_now_add=True)2) в файле settings.py создать конфигурации для логирования,в качестве примера:LOGGING = {'version': 1,'disable_existing_loggers': False,'handlers': {'filehandler': {'level': 'INFO','class': 'django_logger.handler.FileLogHandler','filename': file_log}},'loggers': {'registry': {'handlers': ['filehandler'],'level': 'INFO','propagate': False,}}}3) создать представление CreateViews, для записи логов в базу данных,и обернауть его в @csrf_exempt декоратор,в качестве примера:@csrf_exemptdef create_log(request):strings = request.POSTfor key in strings:string = json.loads(strings[key])default_log_data = string['default_log_data']extra_data = string['extra_data']Log.objects.create(level=default_log_data['level'],message=default_log_data['message'],extra=extra_data)return HttpResponse()4) в файле с views-хами создать строку с обращением к конфигурации логгера:logger = logging.getLogger('registry')и в теле представление, при отработки которого будут записываться логи, прописать:logger.info(message, extra={})где message="сообщение, передоваемое в логгер при отработки представления",а extra="словарь с данными, определяемыми самим пользователем"5) в файле settings.py указать переменые:file_log="путь к файлу, в который будут записываться логи",log_url="урл, по которому будут отправляться логи из файла, для записи в бузу данных"periodicity_of_sending_logs="переодичность отправки логов на запись"6) в settings.py, в INSTALLED_APPS добавить наш django_logger,это нужно, чтобы получить возможность запуска manage.py комманды из пакета django_logger.7) после запуска приложения зпустить manage.py комманду "command_log_user_actions" из коммандной строки,она отправляет логи, записанные в файл, на запись в нашу CreateViews, каждый определенный промежуток времени,указанный в переменной periodicity_of_sending_logs.
Package: django-logger-panel
django-logger-panelAn easy way to change the log level in runtimeInstallationpip install django-logger-panelFeaturesList all active loggers .Change any logger level in run time.Change all logger levels at once.Display logger information.Settings.pyINSTALLED_APPSAddloggerpanelto installed appsINSTALLED_APPS=[...'django_logger_panel',]LOGGINGMake sure theroothas ahandlerset at theLOGGINGdictionary insettings.py, as described in theDjango Documentation.This is therootloggerconfiguration and will allow allloggerswith nohandlerto inherit it from theroot.Example:LOGGING={'version':1,'disable_existing_loggers':False,'formatters':{'console':{'format':'%(asctime)s%(levelname)-8s%(name)-12s%(message)s',},},'handlers':{'console':{'class':'logging.StreamHandler','formatter':'console',},},'root':{'level':'DEBUG','handlers':['console'],},}LOGGER_PANEL_BASE_URLOptionally, change the default base url/loggers/by setting the propertyLOGGER_PANEL_BASE_URL.
This variable is not required.LOGGER_PANEL_BASE_URL="/another-path/"urls.pyAdd thedjango_logger_panel.urlsto theurlpatterns.urlpatterns=[...path("",include("django_logger_panel.urls")),...]ScreenshotsLogger PanelLogger DetailsREST APIList loggersCurl Example:curlhttp://localhost:8000/loggers/-H'Accept:application/json'Response:{"log_levels":{"CRITICAL":50,"ERROR":40,"WARNING":30,"INFO":20,"DEBUG":10,"NOTSET":0},"loggers":[{"name":"_all_loggers_","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":0,"name":"NOTSET"},"parent":null},{"name":"root","level":{"code":30,"name":"WARNING"},"effectiveLevel":{"code":30,"name":"WARNING"},"parent":null},{"name":"django","level":{"code":20,"name":"INFO"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"root"},{"name":"django.db.backends","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django"},{"name":"django.request","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django"},{"name":"django.server","level":{"code":20,"name":"INFO"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django"},{"name":"django.security.csrf","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django"},{"name":"django.db.backends.schema","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django.db.backends"}]}Return a single loggerCurl Example:curlhttp://localhost:8000/loggers/django.db.backends-H'Accept:application/json'Response:{"name":"django.db.backends","level":{"code":0,"name":"NOTSET"},"effectiveLevel":{"code":20,"name":"INFO"},"parent":"django"}Change logger levelCurl Example:curl-XPOSThttp://localhost:8000/loggers/django.db.backends-d'{"logger_level": "DEBUG"}'Response:{"name":"django.db.backends","level":{"code":10,"name":"DEBUG"},"effectiveLevel":{"code":10,"name":"DEBUG"},"parent":"django"}
Package: django_loggers_test
Django Loggers TestA simple tester of Django's loggers' configuration.ContentInstallationUsageInstallationThe easiest way to get this is from PyPI:pipinstalldjango_loggers_testUsageRun your project's shell (python manage.py shell), and then>>>fromdjango_loggers_testimportloggers_test>>>loggers_test()This will log messages to the console, using all available formatters and
levels. There isn't really much more to it, apart from minor configurability.
For details, run>>>help(loggers_test)
Package: django-logging-context
django-logging-contextDescriptiondjango-logging-contextis BSD licensed library extending default django
logging context with following additional values:request id,request duration,remote address,response length,user id,username.Quick startinstall the library:pipinstalldjango-logging-context-yAdddjango-logging-contextto yourINSTALLED_APPSsetting like this:INSTALLED_APPS=[...'django_logging_context',]Add proxy middleware to yourMIDDLEWAREsetting like this:MIDDLEWARE=['django_logging_context.middlewares.LoggingContextMiddleware',...]It's important to place thisLoggingContextMiddlewareat the first place in
aMIDDLEWAREto allow to calculate duration of response more precisely.If you just want to add info about request duration and request id to your
log records then you can useLoggingWSGIMiddlewarein yourwsgi.pylike
this:fromdjango_logging_context.wsgiimportLoggingWSGIMiddlewareapplication=LoggingWSGIMiddleware(get_wsgi_application())Use this example of logging setting to set up your loggers correctlyimportosLOG_LEVEL=os.environ.get('LOG_LEVEL','INFO')DB_LOG_LEVEL=os.environ.get('DB_LOG_LEVEL',LOG_LEVEL)REQUESTS_LOG_LEVEL=os.environ.get('REQUESTS_LOG_LEVEL',LOG_LEVEL)CELERY_LOG_LEVEL=os.environ.get('CELERY_LOG_LEVEL',LOG_LEVEL)SENTRY_LOG_LEVEL=os.environ.get('SENTRY_LOG_LEVEL',LOG_LEVEL)LOGGING={'version':1,'loggers':{'django':{'level':LOG_LEVEL},'django.db':{'level':DB_LOG_LEVEL},'urllib3':{'level':REQUESTS_LOG_LEVEL},'celery':{'level':CELERY_LOG_LEVEL},'sentry':{'level':SENTRY_LOG_LEVEL},},'root':{'level':LOG_LEVEL,'handlers':['console']},'handlers':{'console':{'class':'logging.StreamHandler','formatter':'verbose','filters':['extending_context_filter']}},'filters':{'extending_context_filter':{'()':'django_logging_context.logging.ContextExtendingFilter'}},'formatters':{'verbose':{'format':('[django]%(levelname)s%(asctime)s''%(name)s/%(module)s''%(process)d/%(thread)d'' request_id:%(request_id)s'' remote_addr:%(remote_addr)s'' user_id:%(user_id)s'' username:%(username)s'' duration:%(response_duration)s'' uri:%(uri)s''%(message)s')},},}Log records example[django] INFO 2021-04-08 18:12:13,573 django.server/basehttp 47385/123145535799296 request_id: ea9a2dfd-a662-4632-84d0-d0c5151b5422 remote_addr: 127.0.0.1 user_id: 2 username: root duration: 1.548695s uri: http://127.0.0.1:8000/login/?next=/ "GET /admin/ HTTP/1.1" 200 46937
Package: django-logging-endpoint
> Provide an endpoint to receive logs and push them to a configurable django loggerUsageInstallationInstall the package:pip install django-logging-endpointInstall the application by adding it to the INSTALLED_APPS setting:INSTALLED_APPS += ('logging_endpoint',)Set the logger name, if you want to send the messages to a specific one:LOGGING_ENDPOINT_LOGGER = 'LoggingEndpoint'Set the log message handler function, if you want to customize the parsing of your log messages:LOGGING_ENDPOINT_MESSAGE_HANDLER = 'logging_endpoint.message_handler.default_handler'Add the url to your urls.py:from django.conf.urls import include

urlpatterns += url(r'^logs', include('logging_endpoint.urls'))EndpointsrootThe root endpoint ofdjango-logging-endpointreceives a json message
with the logs to be sent to the configured logger:{
    'message':   'my log message',
    'logger':    'user interaction',
    'loglevel':  'error',
    'timestamp': '2020-01-01T12:00Z'
}By default, a list of logs can be received and will be expanded to the Django
logger. See the documentation’s settings chapter for more information on that.DevelopmentMakefileThis project uses a Makefile for various tasks. Some of the available tasks
are listed below.make clean- Clean build artifacts out of your projectmake test- Run Testsmake plain-test- Run Tests without rebuilding the projectmake sdist- Build a Python source distributionmake docs- Build the Sphinx documentationmake lint- Get a codestyle report about your codemake plain-lint- Get a codestyle report without rebuilding the projectmake- Equivalent tomake test lint docs sdist
Package: django-logging-eventlog
django-logging-eventlogLogger for the logging module that writes messages to the django databaseInstallationInstall using pip:pip install --upgrade django-logging-eventlogModify yoursettings.py. Addeventlogto yourINSTALLED_APPS:INSTALLED_APPS = [
    #django apps
    'eventlog',
    #your apps
]ConfigureLOGGINGin yoursettings.pyfor example:LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'eventlog': {
            'class': 'eventlog.services.EventLogHandler'
        },
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'root': {
            'handlers': ['console', 'eventlog'],
            'level': 'INFO',
            'propagate': True,
        },
    }
}Runpython manage.py makemigrations eventlogand run Runpython manage.py migrateUsageimportlogginglogger=logging.getLogger(__name__)logger.info('info')logger.debug('debug')logger.error('error')logger.critical('critical')logger.warning('warning')try:1/0exceptExceptionasex:logger.exception(ex,exc_info=ex)To prune the eventlog, use the command aspruneeventlog.
For example, to keep records in the database only for the last 30 days, run:python manage.py pruneeventlog 30
Package: django-logging-handlers
Django logging handlersDjango logging handlers is a collection of handlers for logging messages to various services, such as Telegram, Slack, Discord, and more.Quick startInstall via pippipinstalldjango-logging-handlersAdddjango-logging-handlersto your INSTALLED_APPS setting like thisINSTALLED_APPS=[...'django_logging_handlers',]Register LoggingLOGGING={..."handlers":{..."telegram":{"level":"ERROR","class":"django_logging_handlers.handlers.TelegramHandler","token":"<telegram bot token>","chat":"<chat id>","message":"",# optional: if you want to add a message together#           with the traceback"file_name":PROJECT_NAME,# optional: if you want to edit the file name,#           defaults to "traceback.html"},},"loggers":{"django.request":{"handlers":[...,"telegram"],"level":"ERROR","propagate":True,},},}Live FeaturesTelegramPlanned featuresSlackDiscord
Package: django-logging-into-db
Django модуль для логирования ошибок в базу данныхМодуль создан для удобства просмотра логов сервера через админ-панель Django.Каждая запись лога содержит следущую информацию:часть url страницы сайта, на которой возникла ошибка (в случае, когда ошибка возникла на главной, то значение поля будет "/");название исключения;описание исключения;текст traceback;url перехода на страницу, на которой возникла ошибка;дата и время возникновения ошибки.Настройка и запускВ setting.pyдобавить в INSTALLED_APPS'dblog.apps.DblogConfig'добавить в MIDDLEWARE'dblog.middleware.ExceptionLoggingMiddleware'Использование logurulogger.configure(handlers=[{'sink': LoguruDbHandler('id_place_of_log')}])
logger.warning('message')Выполнитьpython3 manage.py migrate
Package: django-logging-middleware
Django Logging MiddlewareThe extension fordjangoto log requests and responses usingloguru.Sometimes code in django views becomes messy because we log requests and response. Also it takes a lot of time to write logs in every view. Using this extension for django, logging becomes simple: all you need is five minutes of installing this package and setting configuration!Requirementspython >=3.6django >=3.0django rest framework >= 3.10 (optional)InstallationInstall usingpip...pip install django-logging-middlewareAdd'logging_middleware'to yourINSTALLED_APPSsetting.INSTALLED_APPS = [ 
    ... 
    'logging_middleware'
]Add setting in yoursettings.py:DJANGO_LOGGING_MIDDLEWARE = {
    'DEFAULT_FORMAT': False,
    'MESSAGE_FORMAT': "<b><green>{time}</green> <cyan>{message}</cyan></b>"
}Add'logging_middleware.middlewares.DjangoLoggingMiddleware'to yourMIDDLEWAREsetting.MIDDLEWARE = {
    ...
    'logging_middleware.middlewares.DjangoLoggingMiddleware'
}Note'logging_middleware.middlewares.DjangoLoggingMiddleware'should be last in the listMIDDLEWAREYou are ready to see log messages like ones below!...
2021-01-08T23:39:33.597138 Request URL: http://localhost:8000/restframework/simple/class/with_query_string/?data=data
2021-01-08T23:39:33.597530 Request METHOD: PUT
2021-01-08T23:39:33.597874 Request HEADERS: {'Cookie': '', 'Content-Length': '26', 'Content-Type': 'application/json'}
...ConfigurationIf you missed 4th step ininstallation, default settings would be:DJANGO_LOGGING_MIDDLEWARE = {
    'DEFAULT_FORMAT': True,
    'MESSAGE_FORMAT': "<b><green>{time}</green> <cyan>{message}</cyan></b>"
}Settings'DEFAULT_FORMAT''DEFAULT_FORMAT'by default isTrue. It means middleware will use default string format for log messages. By setting it toFalse, you should provide in'MESSAGE_FORMAT'your own string format.'MESSAGE_FORMAT''MESSAGE_FORMAT'sets the format of log messages. By default is'<b><green>{time}</green> <cyan>{message}</cyan></b>'. For making your own format string, please look theloguru docs. Note if you set'DEFAULT_FORMAT'asTrue, but also set custom string format in'MESSAGE_FORMAT', the log messages will take the default format. Also by setting'DEFAULT_FORMAT'as False without providing the'MESSAGE_FORMAT', the format of messages will be default.LicenseMIT-License, see LICENSE file.
Package: django-logging-requests
LoggingMiddleware для логирования request запросов на endpoint.Quick startAdd "django_logging" to your INSTALLED_APPS setting like this.INSTALLED_APPS=[...'django_logging',...]Createlogginghandlers withLOGGINGname withinsettings.py. The middleware uses handlers with names:info_loggeranderror_logger.LOGGING={'formatters':{...},'handlers':{...},'loggers':{'info_logger':{'handlers':['info'],'level':'INFO'},'error_logger':{'handlers':['error'],},}}CreateLOGGING_SERVER_NAMEwithingsettings.py. The middleware uses this variable as server name key in every log message.LOGGING_SERVER_NAME='server name'CreateAUTHENTICATION_HEADERwithinsettings.py. The middleware try to get user information from this header injwtformat.AUTHENTICATION_HEADER='Authentication'Add a middleware class to listen in on responsesMIDDLEWARE=[...,"django_logging.middleware.LoggingMiddleware",...,]It's better to set as low as possible.ReleasePushing to master branch will run auto build new version and push it topypi. Before pushing to master
branch must update version insetup.py.
Package: django-loggit
=====Loggit=====Loggit is a django app to record that a certain event transpired. Perhaps acustomer made a purchase. Maybe an email was sent, or an order was shipped.Whatever domain specific events exist, make a record of them. Loggit shipswith a couple of basic models and is easily extended.Detailed info is in the 'docs' directory.Quick Start-----------1. Add "loggit" to your INSTALLED_APPS setting like this::INSTALLED_APPS = (...'loggit',)And define::LOGGIT_LOGENTRY_MODEL = '<app_label>.<ModelName>'LOGGIT_LOGEVENT_MODEL = '<app_label>.<ModelName>'i. Optionally install django-generic-m2m. Provided in django-loggit are twomixins that will add support for adding a generic M2M relationship to alog entry, where objects can be added with a particular label and then willbe coalesced into the context that can be used by the event's render method.See https://github.com/coleifer/django-generic-m2m .2. IMPORTANT: Loggit uses swappable models for its models. This is done so thateither the LogEntry or the LogEvent model can be replaced with something thatimplements the same interface. However...For projects on Django 1.7+, thismeans that whichever models you use when you do Loggit's first migrations,must be the models you use for the lifetime of that project (i.e. migrations).Read about how migrations handle django.contrib.auth and its swappablemodel for more information.3. Run `python manage.py migrate` to create the taggit models. Before runnning,make sure LOGGIT_LOGENTRY_MODEL and LOGGIT_LOGEVENT_MODEL are set to themodels you would like them to be for the lifetime of the project.4. Start creating events based on your domain, and implement how you want themto be rendered.
Package: django-logicaldelete
This is a small and simple app that I threw together to get some reuse out of
something I do in nearly every project and every model I create.  It’s too easy
for good data to get deleted and it be unrecoverable.  It’s also too easy to
fix this by overriding the model’s delete() method and just flagging records
as deleted and then leveraging Django’s Managers to override default behavior
so that logically deleted items are not returned in querysets.There are two exceptions however, that I have found useful to this rule.In the admin I like to see everything with an indicator of whether or not
it has been deleted, with the ability to filter down to just active records,
(or deleted for that matter).I still think it is a valid request when an item is fetched for by it’s
primary key value, that the object should return, even if it is marked as
deleted.Installing django-logicaldeletepip install django-logicaldeleteUsing django-logicaldeleteUsing the app is pretty simple:addlogicaldeleteto your INSTALLED_APPSInherit fromlogicaldelete.models.Modelfor all models that you wish to
share in this functionality.Create and/or Register admins for each of these models usinglogicaldelete.admin.ModelAdminAdditionalLogical deletes are handled by date stamping adate_removedcolumn.  In addition, adate_createdanddate_modifiedcolumns will be populated as a convenience.Backwards Incompatible Changes1.1Changedeverythingtoall_with_deletedon LogicalDeleteManagerLogicalDeleteManager moved fromlogicaldelete.modelstologicaldelete.managersRemoveddeletedandeverythingquerysets fromlogicaldelete.models.Model