k8s应用内部日志收集

k8s应用内部日志收集


k8s应用内部日志收集_第1张图片
日志收集架构图
问题描述:将pod的日志文件通过emptydir方式挂载出来,但是kubelet挂载出来的日志文件目录默认只有podID名,很难辨别日志文件是那个pod,那个containers的。

解决方案:在pod创建的时候通过软链接将podname,namespace,containersname,containerid等信息对应到pod的日志目录,从而解决上述问题。

源码改动:

1.k8s/pkg/kubelet/dockertools/docker_manager.go
func  (dm  * DockerManager)  runContainerInPod() 方法添加

//软链接/var/lib/kubelet/pods   获取容器的pod名,用于Elasticsearch日志搜集服务
//   /var/lib/kubelet/pods/+podUID+/volumes/kubernetes.io~empty-dir/data/*- >/var/log/containers/applog.podName.containerName.id.log
    for i := 0; i < len(pod.Spec.Volumes); i++ {
        if pod.Spec.Volumes[i].EmptyDir != nil {
            emptydirname := pod.Spec.Volumes[i].Name
            cname := container.Name
            str := "logdir" + cname
            if emptydirname == str && cname != "POD" {
                podUID := kubecontainer.GetPodUID(pod)
                containerLogFile_emptdir := path.Join("/var/lib/kubelet/pods", podUID, "volumes/kubernetes.io~empty-dir", emptydirname)
                symlinkFile_emptdir := LogSymlink_emptdir(dm.containerLogsDir, kubecontainer.GetPodFullName(pod), container.Name, id.ID)
                if err = dm.os.Symlink(containerLogFile_emptdir, symlinkFile_emptdir); err != nil {
                    glog.Errorf("Failed to create symbolic link to the application's log file of pod %q container %q: %v", format.Pod(pod), container.Name, err)
                }
            }
        }
    }
1.k8s/pkg/kubelet/dockertools/docker.go
func LogSymlink_emptdir(containerLogsDir, podFullName, containerName, dockerId string) string {
    return path.Join(containerLogsDir, fmt.Sprintf("applog.%s.%s.%s.%s", podFullName, containerName, dockerId, LogSuffix))
}

实验效果:
在/var/log/containers下可以看到容器内应用日志的软链接,进而可以获取到emtpdir挂载出来日志对应的podname,containername,id



  • ES结果:
  • "_index""logstash-2016.10.19",
  • "_type""fluentd",
  • "_id""AVfcB42cEKo1rP0QdbCf",
  • "_version"1,
  • "_score"1,
  • "_source": {
    • "message""test31",
    • "pod_name""test",
    • "namespace_name""default",
    • "container_name""test",
    • "container_id""286ca6a92d26b46342860b19cbba3406f7e9d3d8df41e3497d7f09d055495424",
    • "logdir""3.log",
    • "tag":"k8s.applog.test_default.test.286ca6a92d26b46342860b19cbba3406f7e9d3d8df41e3497d7f09d055495424.log.3.log",
    • "@timestamp""2016-10-19T16:21:03+08:00"
    }

fluentd配置:

  type tail
  format none
  path /var/log/containers/applog*/*
  pos_file /var/log/es-containers-app.log.pos
  time_format %Y-%m-%dT%H:%M:%S.%NZ
  tag reform.*
  read_from_head true



  type record_reformer
  renew_record false
  enable_ruby true
  tag k8s.${tag_suffix[4]}
 
    pod_name ${tag_suffix[5].split('_')[0]}
    namespace_name ${tag_suffix[5].split('_')[1].split('.')[0]}
    container_name ${tag_suffix[6].split('.')[0]}
    container_id ${tag_suffix[7].split('.')[0]}
    logdir ${tag_suffix[9]}
 


你可能感兴趣的:(docker,kubernetes)