(self, record)
| 41 | """A custom file handler that writes simpler plain text log entries.""" |
| 42 | |
| 43 | def emit(self, record): |
| 44 | try: |
| 45 | # Check if stream is available before trying to write |
| 46 | if self.stream is None: |
| 47 | self.stream = self._open() |
| 48 | |
| 49 | # Extract the message from the structlog record |
| 50 | if isinstance(record.msg, dict) and "event" in record.msg: |
| 51 | # Extract the basic message |
| 52 | message = record.msg.get("event", "") |
| 53 | |
| 54 | # Extract additional context |
| 55 | context = { |
| 56 | k: v |
| 57 | for k, v in record.msg.items() |
| 58 | if k not in ("event", "logger", "level", "timestamp") |
| 59 | } |
| 60 | |
| 61 | # Format context if present |
| 62 | context_str = "" |
| 63 | if context: |
| 64 | context_str = " " + " ".join( |
| 65 | f"{k}={v}" for k, v in context.items() if k != "exc_info" |
| 66 | ) |
| 67 | |
| 68 | # Get the logger name from the record or from the structlog context |
| 69 | logger_name = record.msg.get("logger", record.name) |
| 70 | |
| 71 | # Format timestamp |
| 72 | timestamp = datetime.now().strftime(get_timestamp_format()) |
| 73 | |
| 74 | # Create the log entry |
| 75 | log_entry = f"{timestamp} [{record.levelname.ljust(8)}] {message}{context_str} [{logger_name}]\n" |
| 76 | |
| 77 | # Write to file |
| 78 | self.stream.write(log_entry) |
| 79 | self.flush() |
| 80 | |
| 81 | # Handle exception if present |
| 82 | # Check both record.exc_info and the 'exc_info' in the message dict |
| 83 | record_has_exc = record.exc_info and record.exc_info != (None, None, None) |
| 84 | msg_has_exc = "exc_info" in record.msg and record.msg["exc_info"] |
| 85 | |
| 86 | if record_has_exc: |
| 87 | # Use the exception info from the record |
| 88 | tb_str = "".join(traceback.format_exception(*record.exc_info)) |
| 89 | self.stream.write(tb_str + "\n") |
| 90 | self.flush() |
| 91 | elif msg_has_exc and isinstance(record.msg["exc_info"], tuple): |
| 92 | # Use the exception info from the message |
| 93 | tb_str = "".join(traceback.format_exception(*record.msg["exc_info"])) |
| 94 | self.stream.write(tb_str + "\n") |
| 95 | self.flush() |
| 96 | elif msg_has_exc and hasattr(record.msg["exc_info"], "__traceback__"): |
| 97 | # Handle exceptions that are passed directly |
| 98 | exc = record.msg["exc_info"] |
| 99 | tb_str = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) |
| 100 | self.stream.write(tb_str + "\n") |
no test coverage detected