问题描述
因此,我整理了一个基于docker的流利TCP日志收集器。
下面的示例https://docs.fluentd.org/input/tcp导致成功说出了来自主机Win 10 WSL(Debian)的线路
echo "my_service: 08:03:10 INFO [my_py_file:343]: My valuable log info." | netcat 127.0.0.1 5170
这是一个很好的JSON,正如我们所希望的那样。但是我想从python 3.7开始!所以:
import socket
def netcat(hn: str,p: int,content: bytes):
"""https://www.instructables.com/id/Netcat-in-Python/"""
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((hn,p))
sock.sendall(content)
sock.close()
msg_raw = "my_service: 08:03:10 INFO [my_py_file:343]: My valuable log info."
netcat('127.0.0.1',5170,bytes(msg_raw,'utf-8'))
WSL或否:此python脚本始终运行,没有例外。流利的语言也没有任何反应,我无法解释。 可以并且愿意吗?
有任何后果的话:这是我的fluentd.conf
中的相关部分。
<source>
@type tcp
@label mainstream
@id pawc_tcp
tag paws.tcp
port 5170
bind 0.0.0.0
# https://docs.fluentd.org/parser/regexp
<parse>
@type regexp
expression /^(?<service_uuid>[a-zA-Z0-9_-]+): (?<logtime>[^\s]+) (?<loglvl>[^\s]+) \[(?<file>[^\]:]+):(?<line>\d+)\]: (?<msg>.*)$/
time_key logtime
time_format %H:%M:%S
types line:integer
</parse>
</source>
<label mainstream>
<match paws.tcp>
@type file
@id output_tcp
path /fluentd/log/tcp.*.log
symlink_path /fluentd/log/tcp.log
</match>
</label>
解决方法
尝试在邮件末尾发送\r\n
或\0
。该消息以字节为单位通过网络发送,因此可能已存储在缓冲区中,读取缓冲区的代码需要一种方法来知道消息已结束。正则表达式也可以匹配行终止符,因此我认为也是必须的。
如上面的 Alex W 所述,我使用的流利的正则表达式接受TCP行需要\n
。我想添加第二个答案来改善原始问题的python代码。
实际上有一个易于实现的logging.handler.SocketHandler
类!但是,它会查看python日志服务器来腌制其输出。使用流畅的语言意味着必须重写emit
函数才能使用它。之后一切正常。
import logging,logging.handlers
class SocketHandlerBytes(logging.handlers.SocketHandler):
def emit(self,record):
try:
msg = bytes(self.format(record) + "\n",'utf-8')
self.send(msg)
except Exception:
self.handleError(record)
sh = SocketHandlerBytes(host,port)
sh.setFormatter(logger_format_appropriate_for_your_fluentd_tcp_regex)
logging.root.addHandler(sh)