Run subprocess and print output to logging

You could try to pass the pipe directly without buffering the whole subprocess output in memory: from subprocess import Popen, PIPE, STDOUT process = Popen(command_line_args, stdout=PIPE, stderr=STDOUT) with process.stdout: log_subprocess_output(process.stdout) exitcode = process.wait() # 0 means success where log_subprocess_output() could look like: def log_subprocess_output(pipe): for line in iter(pipe.readline, b”): # b’\n’-separated lines logging.info(‘got line from … Read more

Django Setup Default Logging

Figured it out… You set the ‘catch all’ logger by referencing it with the empty string: ”. As an example, in the following setup I have the all log events getting saved to logs/mylog.log, with the exception of django.request log events which will be saved to logs/django_request.log. Because ‘propagate’ is set to False for my … Read more

Naming Python loggers

I typically don’t use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple: import logging LOG = logging.getLogger(__name__) At the top of the module and subsequent: LOG.info(‘Spam and eggs are tasty!’) from anywhere in the file typically gets me to where I want to … Read more

python logging to database

I recently managed to write my own database logger in Python. Since I couldn’t find any example I thought I post mine here. Works with MS SQL. Database table could look like this: CREATE TABLE [db_name].[log]( [id] [bigint] IDENTITY(1,1) NOT NULL, [log_level] [int] NULL, [log_levelname] [char](32) NULL, [log] [char](2048) NOT NULL, [created_at] [datetime2](7) NOT NULL, … Read more

How to write custom python logging handler?

import logging class ProgressConsoleHandler(logging.StreamHandler): “”” A handler class which allows the cursor to stay on one line for selected messages “”” on_same_line = False def emit(self, record): try: msg = self.format(record) stream = self.stream same_line = hasattr(record, ‘same_line’) if self.on_same_line and not same_line: stream.write(self.terminator) stream.write(msg) if same_line: stream.write(‘… ‘) self.on_same_line = True else: stream.write(self.terminator) self.on_same_line … Read more