Skip to content

Logging in Containers — Best Practices for Container Logging

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Logging In Containers. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Container logging follows the principle of writing logs to stdout/stderr, allowing the container runtime to handle log routing and rotation.

// Container-optimized logger
const logger = pino({
  // Write to stdout for container runtime
  destination: pino.destination(1),  // fd 1 = stdout

  // JSON format for log collectors
  formatters: {
    level: (label) => ({ level: label.toUpperCase() })
  },

  // Include container metadata
  mixin() {
    const container = {
      host: os.hostname(),
      pid: process.pid,
      memory: process.memoryUsage().heapUsed
    };

    if (process.env.KUBERNETES_SERVICE_HOST) {
      container.pod = process.env.HOSTNAME;
      container.namespace = fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'utf-8');
    }

    return { container };
  }
});

// Docker logging configuration
// docker-compose.yml x-logging:
//  driver: "json-file"
//  options:
//    max-size: "10m"
//    max-file: "3"
//    tag: "{{.Name}}"

// Kubernetes log collection with sidecar
// apiVersion: v1
// kind: Pod
// spec:
//   containers:
//   - name: scan-app
//     image: scan-app:latest
//     stdout: true
//   - name: log-shipper
//     image: fluentd:latest
//     volumeMounts:
//     - name: varlog
//       mountPath: /var/log
//   volumes:
//   - name: varlog
//     emptyDir: {}

Container logging best practices ensure logs are properly captured by Orchestration platforms and log collectors.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro