logspout 集中查看日志

logspout 可以把某宿主机上所有 docker 容器的日志集中到一起,方便用户查看,本身也可以用 docker 安装:

1
2
3
4
docker run -d --name="logspout" \
--volume=/var/run/docker.sock:/var/run/docker.sock \
--publish=127.0.0.1:8000:80 \
gliderlabs/logspout

这样就可以在命令行查看日志了:

1
2
3
4
5
6
# 查看所有日志
curl http://127.0.0.1:8000/logs
# 查看名以 api 开头的容器的日志
curl http://127.0.0.1:8000/logs/name:api*
# 指定返回 json 格式
curl http://127.0.0.1:8000/logs/name:api* -H 'Accept: application/json'

写成 compose 文件的形式为:

1
2
3
4
5
6
7
8
9
10
version: '3'

services:
logspout:
image: gliderlabs/logspout:latest
volumes:
- /etc/hostname:/etc/host_hostname:ro
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 8000:80

查看源码:

1
2
FROM gliderlabs/logspout:master
ENV SYSLOG_FORMAT rfc3164

build.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/sh
set -e
apk add --update go build-base git mercurial ca-certificates
mkdir -p /go/src/github.com/gliderlabs
cp -r /src /go/src/github.com/gliderlabs/logspout
cd /go/src/github.com/gliderlabs/logspout
export GOPATH=/go
go get
go build -ldflags "-X main.Version=$1" -o /bin/logspout
apk del go git mercurial build-base
rm -rf /go /var/cache/apk/* /root/.glide

# backwards compatibility
ln -fs /tmp/docker.sock /var/run/docker.sock

modules.go

1
2
3
4
5
6
7
8
9
package main

import (
_ "github.com/gliderlabs/logspout/adapters/syslog"
_ "github.com/gliderlabs/logspout/transports/tcp"
_ "github.com/gliderlabs/logspout/transports/tls"
_ "github.com/gliderlabs/logspout/transports/udp"
_ "github.com/looplab/logspout-logstash"
)

那个 fork 可以正确使用 hostname 变量,根据容器所在的主机来动态判断,属于优化范畴了。