How to Set Up Multi-Format Logging (JSON vs Console) in Fabrica-Kit

Initialize Fabrica-Kit's logger with logType set to "zap" for JSON output or any other value for human-readable console logs using the xlog.Init() function.

Fabrica-Kit, the open-source microservices toolkit from Go Pantheon, provides a unified logging interface through the xlog package. This system supports both structured JSON logs for production pipelines and readable console output for local development, all controlled through a single configuration parameter in xlog/log.go.

Understanding the xlog.Init Configuration

The central entry point for logging setup is the Init function located in xlog/log.go. This function accepts a logType parameter that determines which logger implementation is instantiated, along with contextual metadata that gets attached to every log entry.

func Init(logType, logLevel string, profile, color, name, version string, nodeName string) (logger log.Logger)

Parameter breakdown:

  • logType: Determines the output format. The value "zap" selects the high-performance Zap-based logger emitting JSON; any other value falls back to log.DefaultLogger (the Kratos default) for console output.
  • logLevel: Controls filtering with "debug", "info", "warn", or "error".
  • profile, color, name, version, nodeName: Contextual fields automatically injected into every log line (service identity, environment, node identifier).

The implementation uses a switch statement in xlog/log.go to select the concrete logger:

switch logType {
case "zap":
    base = newZapLogger(logLevel)   // → JSON output
default:
    base = log.DefaultLogger        // → console output
}

The function returns a log.Logger interface and registers it globally via log.SetLogger(logger), making it available throughout your application.

JSON Logging for Production

Configuration and Setup

To emit structured JSON logs suitable for log aggregation systems like ELK or Grafana Loki, pass "zap" as the logType. The newZapLogger helper configures zapcore.NewJSONEncoder to produce machine-parseable output.

package main

import (
    "github.com/go-pantheon/fabrica-kit/xlog"
)

func main() {
    // JSON output via Zap
    logger := xlog.Init(
        "zap",          // <- selects JSON encoder
        "info",         // log level
        "prod",         // profile
        "blue",         // color (metadata only)
        "order-service",// service name
        "v2.3.1",       // version
        "node-7",       // node identifier
    )

    // Structured logging – fields are added automatically
    logger.Info("order created", "order_id", 12345)
}

Output Format

Each log line becomes a JSON object containing the message, timestamp, severity, and injected metadata:

{
  "msg":"order created",
  "level":"info",
  "ts":"2024-10-01T12:34:56Z",
  "profile":"prod",
  "color":"blue",
  "caller":"order/main.go:27",
  "svc":"order-service",
  "sver":"v2.3.1",
  "node":"node-7",
  "trace":"0a1b2c3d4e5f6g7h",
  "span":"abcd1234efgh5678",
  "order_id":12345
}

Console Logging for Development

Configuration and Setup

For local development or debugging scenarios requiring human-readable output, use any value other than "zap" (such as "console"). This activates the default Kratos logger which writes plain text to os.Stderr.

package main

import (
    "github.com/go-pantheon/fabrica-kit/xlog"
)

func main() {
    // Console output using the default Kratos logger
    logger := xlog.Init(
        "console",      // any non‑"zap" value → console logger
        "debug",
        "dev",
        "green",
        "auth-service",
        "v0.9.0",
        "node-2",
    )

    logger.Debug("checking token", "token", "abc123")
    logger.Error("failed to connect to DB", "error", err)
}

Output Format

The console format presents timestamp, level, message, and metadata in a single readable line:


2024/10/01 12:34:56.789 [debug] checking token token=abc123 profile=dev color=green svc=auth-service sver=v0.9.0 node=node-2 caller=auth/main.go:23

Runtime Format Switching

You can externalize the format selection via environment variables to switch between JSON and console without recompiling. This pattern allows the same binary to adapt to development versus production environments.

import (
    "os"
    "github.com/go-pantheon/fabrica-kit/xlog"
)

func initLogger() {
    // LOG_FORMAT can be "json" or "console"
    format := os.Getenv("LOG_FORMAT")
    logType := "console"
    if format == "json" {
        logType = "zap"
    }

    xlog.Init(
        logType,
        "info",
        os.Getenv("PROFILE"),
        os.Getenv("LOG_COLOR"),
        os.Getenv("SERVICE_NAME"),
        os.Getenv("SERVICE_VERSION"),
        os.Getenv("NODE_NAME"),
    )
}

Summary

  • Single function setup: Use xlog.Init() in xlog/log.go to configure logging across your Fabrica-Kit services; the function returns a log.Logger and registers it globally.
  • JSON for production: Set logType to "zap" to enable structured JSON output via the Zap encoder.
  • Console for development: Use any non-"zap" value for logType to fall back to the human-readable Kratos default logger.
  • Automatic metadata injection: The Init function automatically attaches service name, version, node identifier, profile, and color to every log entry.
  • Runtime flexibility: Switch formats dynamically using environment variables to adapt to different deployment environments without code changes.

Frequently Asked Questions

What log levels are supported in fabrica-kit?

Fabrica-Kit supports four standard severity levels: "debug", "info", "warn", and "error". Pass the desired level to xlog.Init() as the second parameter; logs below this threshold will be filtered out by the underlying Zap or Kratos implementation.

How do I switch between JSON and console logging dynamically?

Check an environment variable at startup (such as LOG_FORMAT) and map "json" to logType="zap" and "console" to any other value before calling xlog.Init(). This allows the same binary to emit structured logs in production and readable lines during local development.

Does fabrica-kit support custom log formats beyond JSON and console?

Currently, the xlog package provides two built-in implementations: the Zap-based JSON logger (activated by "zap") and the default Kratos console logger (fallback). Custom encoders would require extending the switch logic in xlog/log.go or implementing a custom log.Logger interface wrapper.

Where is the logging initialization logic located in the source code?

The core logging implementation resides in xlog/log.go within the go-pantheon/fabrica-kit repository. This file contains the Init function, the logType switch statement, and the newZapLogger helper that configures the JSON encoder and log level.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →