You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用SysLogHandler远程日志同线带#000<xx>标识问题求解

问题原因

  • Python内置SysLogHandler默认会在每条日志前添加PRI优先级头,格式为<优先级数值>,你看到的<15>、<10>就是这个字段
  • TCP协议是流传输,SysLogHandler默认不会为每条日志添加分隔符,多条日志会被粘包发送到服务端,服务端解析异常时就会插入#000(NUL空字符的可视化表示)作为填充,同时所有日志拼接成一行

解决方案

自定义继承SysLogHandler,去掉默认的PRI头拼接逻辑,同时为每条TCP日志添加换行符作为分隔,修改后的完整代码如下:

#!/usr/bin/env python3
import logging
import logging.handlers
import socket

class CustomSysLogHandler(logging.handlers.SysLogHandler):
    def emit(self, record):
        try:
            # 仅使用自定义格式化后的内容,不添加默认PRI头
            msg = self.format(record)
            # TCP模式添加换行作为分隔符,避免粘包
            if self.socktype == socket.SOCK_STREAM:
                msg += '\n'
                self.socket.sendall(msg.encode('utf-8'))
            else:
                # UDP模式保留原有逻辑,可按需修改
                super().emit(record)
        except Exception:
            self.handleError(record)

# 原有业务逻辑不变,仅替换Handler实现
formatterV = logging.Formatter('[%(name)s]-%(levelname)s: %(message)s')
logger = logging.getLogger('MyLogger')
handler = CustomSysLogHandler(address=('xxx.xxx.xxx.xxx',514), socktype=socket.SOCK_STREAM)
handler.setFormatter(formatterV)
logger.addHandler(handler)
logger.setLevel(level=logging.DEBUG)

logger.debug('this is debug')
logger.debug('this is debug2')
logger.critical('this is critical')

效果验证

修改后服务端收到的日志格式如下,每条单独成行无多余标识:

Oct  6 14:53:09 xxx.xxx.xxx.xxx  [MyLogger]-DEBUG: this is debug
Oct  6 14:53:09 xxx.xxx.xxx.xxx  [MyLogger]-DEBUG: this is debug2
Oct  6 14:53:09 xxx.xxx.xxx.xxx  [MyLogger]-CRITICAL: this is critical

内容的提问来源于stack exchange,提问作者Sketch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:30:03