Files

68 lines
1.5 KiB
Go
Raw Permalink Normal View History

package common
import (
"fmt"
"io"
"log"
"log/slog"
"net/http"
"os"
"path/filepath"
)
func EnvOr(key, fallback string) string {
if val := os.Getenv(key); val != "" {
return val
}
return fallback
}
func PrefixMiddleware(prefix string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}
}
// InitLogger configures structured JSON logging for a tool.
// It ensures the log directory exists, opens logs/<toolName>.log,
// and configures slog and log to output there.
func InitLogger(toolName string) *os.File {
logPath := os.Getenv("LOG_FILE")
if logPath == "" {
logPath = filepath.Join("logs", toolName+".log")
}
dir := filepath.Dir(logPath)
if dir != "" {
_ = os.MkdirAll(dir, 0755)
}
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open log file %s: %v\n", logPath, err)
}
var writer io.Writer = os.Stdout
if logFile != nil {
if os.Getenv("MANAGED_BY_GATEWAY") == "1" {
// Managed by gateway: gateway redirects stdout/stderr to logFile,
// writing directly to logFile ensures immediate availability.
writer = logFile
} else {
// Standalone run: duplicate to both stdout and log file
writer = io.MultiWriter(os.Stdout, logFile)
}
}
logger := slog.New(slog.NewJSONHandler(writer, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
log.SetOutput(writer)
return logFile
}