• Stars
    star
    138
  • Rank 264,508 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

xlog is a logger for net/context aware HTTP applications

⚠️ Check zerolog, the successor of xlog.

HTTP Handler Logger

godoc license Build Status Coverage

xlog is a logger for net/context aware HTTP applications.

Unlike most loggers, xlog will never block your application because one its outputs is lagging. The log commands are connected to their outputs through a buffered channel and will prefer to discard messages if the buffer get full. All message formatting, serialization and transport happen in a dedicated go routine.

Read more about xlog on Dailymotion engineering blog.

Features

  • Per request log context
  • Per request and/or per message key/value fields
  • Log levels (Debug, Info, Warn, Error)
  • Color output when terminal is detected
  • Custom output (JSON, logfmt, …)
  • Automatic gathering of request context like User-Agent, IP etc.
  • Drops message rather than blocking execution
  • Easy access logging thru github.com/rs/xaccess

Works with both Go 1.7+ (with net/context support) and Go 1.6 if used with github.com/rs/xhandler.

Install

go get github.com/rs/xlog

Usage

c := alice.New()

host, _ := os.Hostname()
conf := xlog.Config{
    // Log info level and higher
    Level: xlog.LevelInfo,
    // Set some global env fields
    Fields: xlog.F{
        "role": "my-service",
        "host": host,
    },
    // Output everything on console
    Output: xlog.NewOutputChannel(xlog.NewConsoleOutput()),
}

// Install the logger handler
c = c.Append(xlog.NewHandler(conf))

// Optionally plug the xlog handler's input to Go's default logger
log.SetFlags(0)
xlogger := xlog.New(conf)
log.SetOutput(xlogger)

// Install some provided extra handler to set some request's context fields.
// Thanks to those handler, all our logs will come with some pre-populated fields.
c = c.Append(xlog.MethodHandler("method"))
c = c.Append(xlog.URLHandler("url"))
c = c.Append(xlog.RemoteAddrHandler("ip"))
c = c.Append(xlog.UserAgentHandler("user_agent"))
c = c.Append(xlog.RefererHandler("referer"))
c = c.Append(xlog.RequestIDHandler("req_id", "Request-Id"))

// Here is your final handler
h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Get the logger from the request's context. You can safely assume it
    // will be always there: if the handler is removed, xlog.FromContext
    // will return a NopLogger
    l := xlog.FromRequest(r)

    // Then log some errors
    if err := errors.New("some error from elsewhere"); err != nil {
        l.Errorf("Here is an error: %v", err)
    }

    // Or some info with fields
    l.Info("Something happend", xlog.F{
        "user":   "current user id",
        "status": "ok",
    })
    // Output:
    // {
    //   "message": "Something happend",
    //   "level": "info",
    //   "file": "main.go:34",
    //   "time": time.Time{...},
    //   "user": "current user id",
    //   "status": "ok",
    //   "ip": "1.2.3.4",
    //   "user-agent": "Mozilla/1.2.3...",
    //   "referer": "http://somewhere.com/path",
    //   "role": "my-service",
    //   "host": "somehost"
    // }
}))
http.Handle("/", h)

if err := http.ListenAndServe(":8080", nil); err != nil {
    xlogger.Fatal(err)
}

Copy Logger

You may want to get a copy of the current logger to pass a modified version to a function without touching the original:

l := xlog.FromContext(ctx)
l2 := xlog.Copy(l)
l2.SetField("foo", "bar")

Make sure you copy a request context logger if you plan to use it in a go routine that may still exist after the end of the current request. Contextual loggers are reused after each requests to lower the pressure on the garbage collector. If you would use such a logger in a go routine, you may end up using a logger from another request/context or worse, a nil pointer:

l := xlog.FromContext(ctx)
l2 := xlog.Copy(l)
go func() {
    // use the safe copy
    l2.Info("something")
}()

Global Logger

You may use the standard Go logger and plug xlog as it's output as xlog implements io.Writer:

xlogger := xlog.New(conf)
log.SetOutput(xlogger)

This has the advantage to make all your existing code or libraries already using Go's standard logger to use xlog with no change. The drawback though, is that you won't have control on the logging level and won't be able to add custom fields (other than ones set on the logger itself via configuration or SetFields()) for those messages.

Another option for code you manage but which is outside of a HTTP request handler is to use the xlog provided default logger:

xlog.Debugf("some message with %s", variable, xlog.F{"and": "field support"})

This way you have access to all the possibilities offered by xlog without having to carry the logger instance around. The default global logger has no fields set and has its output set to the console with no buffering channel. You may want to change that using the xlog.SetLogger() method:

xlog.SetLogger(xlog.New(xlog.Config{
    Level: xlog.LevelInfo,
    Output: xlog.NewConsoleOutput(),
    Fields: xlog.F{
        "role": "my-service",
    },
}))

Configure Output

By default, output is setup to output debug and info message on STDOUT and warning and errors to STDERR. You can easily change this setup.

XLog output can be customized using composable output handlers. Thanks to the LevelOutput, MultiOutput and FilterOutput, it is easy to route messages precisely.

conf := xlog.Config{
    Output: xlog.NewOutputChannel(xlog.MultiOutput{
        // Send all logs with field type=mymodule to a remote syslog
        0: xlog.FilterOutput{
            Cond: func(fields map[string]interface{}) bool {
                return fields["type"] == "mymodule"
            },
            Output: xlog.NewSyslogOutput("tcp", "1.2.3.4:1234", "mymodule"),
        },
        // Setup different output per log level
        1: xlog.LevelOutput{
            // Send errors to the console
            Error: xlog.NewConsoleOutput(),
            // Send syslog output for error level
            Info: xlog.NewSyslogOutput("", "", ""),
        },
    }),
})

h = xlog.NewHandler(conf)

Built-in Output Modules

Name Description
OutputChannel Buffers messages before sending. This output should always be the output directly set to xlog's configuration.
MultiOutput Routes the same message to several outputs. If one or more outputs return error, the last error is returned.
FilterOutput Tests a condition on the message and forward it to the child output if true.
LevelOutput Routes messages per level outputs.
ConsoleOutput Prints messages in a human readable form on the stdout with color when supported. Fallback to logfmt output if the stdout isn't a terminal.
JSONOutput Serialize messages in JSON.
LogfmtOutput Serialize messages using Heroku like logfmt.
LogstashOutput Serialize JSON message using Logstash 2.0 (schema v1) structured format.
SyslogOutput Send messages to syslog.
UIDOutput Append a globally unique id to every message and forward it to the next output.

Third Party Extensions

Project Author Description
gRPClog Hugo González Labrador An adapter to use xlog as the logger for grpclog.
xlog-nsq Olivier Poitrey An xlog to NSQ output.
xlog-sentry trong An xlog to Sentry output.

Licenses

All source code is licensed under the MIT License.

More Repositories

1

zerolog

Zero Allocation JSON Logger
Go
10,343
star
2

xid

xid is a globally unique id generator thought for the web
Go
3,874
star
3

curlie

The power of curl, the ease of use of httpie.
Go
2,808
star
4

cors

Go net/http configurable handler to handle CORS requests
Go
2,625
star
5

rest-layer

REST Layer, Go (golang) REST API framework
Go
1,257
star
6

SDSegmentedControl

A drop-in remplacement for UISegmentedControl that mimic iOS 6 AppStore tab controls
Objective-C
1,200
star
7

pushd

Blazing fast multi-protocol mobile and web push notification service
CoffeeScript
1,162
star
8

jplot

iTerm2 expvar/JSON monitoring tool
Go
1,140
star
9

SDAVAssetExportSession

AVAssetExportSession drop-in replacement with customizable audio&video settings
Objective-C
800
star
10

SDURLCache

URLCache subclass with on-disk cache support on iPhone/iPad
Objective-C
798
star
11

SafariTabSwitching

A SIMBL plugin for Safari 5.1 allowing tab switching by index (using Cmd-1, Cmd-2…)
Objective-C
472
star
12

jaggr

JSON Aggregation CLI
Go
460
star
13

SafariOmnibar

Safari plugin to add Chrome like omnibar in Safari
Objective-C
416
star
14

dnstrace

DNS resolution tracing tool
Go
270
star
15

dnscache

DNS lookup cache for Go
Go
267
star
16

node-netmask

Parse and lookup IP network blocks
CoffeeScript
253
star
17

xhandler

XHandler is a bridge between net/context and http.Handler
Go
233
star
18

seamless

Seamless restart / zero-downtime deploy for Go servers
Go
107
star
19

xmux

xmux is a httprouter fork on top of xhandler (net/context aware)
Go
98
star
20

vast

Golang VAST 3.0 library
Go
83
star
21

xstats

xstats is a generic client for service instrumentation
Go
82
star
22

gls

A graphical ls command for iTerm2 with icons
Swift
78
star
23

SDNetworkActivityIndicator

Handle show/hiding of the iOS network activity indicator
Objective-C
75
star
24

zkfarmer

ZkFarmer is a set of tools to easily manage distributed server farms using Apache ZooKeeper
Python
74
star
25

logbench

Golang logging library benchmarks
Go
69
star
26

dashplay

Easy dashboard screen management
HTML
67
star
27

SDAdvancedWebView

Add some handy features to you UIWebViews
Objective-C
49
star
28

eve-auth-jwt

Eve OAuth 2.0 JWT token validation authentication module
Python
46
star
29

domcheck

A Python library to validate the ownership of a domain using different strategies
Python
45
star
30

iris-ice

Iris keyboard build with custom case
43
star
31

scanman

ScanSnap manager for Raspberry Pi
Python
40
star
32

formjson

Go net/http handler to transparently manage posted JSON
Go
39
star
33

moquette

MQTT service dispatcher
Go
38
star
34

SDReachability

Easy to use and to embed Reachability library
Objective-C
36
star
35

golp

Go panic logger
Go
27
star
36

xaccess

Go http handler access logger
Go
20
star
37

tzsp

TaZmen Sniffer Protocol (TZSP) parser in Go
Go
20
star
38

rest-layer-mongo

REST Layer MongoDB resource storage handler
Go
18
star
39

audience-meter

Lightweight server to mesure audience of a live event
JavaScript
17
star
40

node-dnsstamp

DNS Stamp encoding/decoding library for node
TypeScript
15
star
41

net-server-mail

Extensible Perl implementation of the STMP protocol and its different evolutions (ie: ESMTP, LMTP)
Perl
15
star
42

vmap

Golang VMAP 1.0 library
Go
14
star
43

SDSRTParser

Objective-C SRT subtitle parser
Objective-C
13
star
44

mysql-genocide

Parallel operations on MySQL processlist
Perl
11
star
45

dnsdump

DNS Packet Dump
Go
10
star
46

pinba_http

Pinba HTTP Gateway
Python
8
star
47

gh-readme

Githup pages template for projects README
CSS
7
star
48

rest-layer-es

REST Layer ElasticSearch resource storage handler
Go
6
star
49

mydbd

A mysqli OO interface with PEAR::DB API compatibility
PHP
5
star
50

local-ip

Go
4
star
51

rest-layer-mem

REST Layer memory storage handler
Go
4
star
52

homebrew-tap

rs homebrew packages
Ruby
3
star
53

xlog-nsq

XLog to NSQ Output
Go
3
star
54

rest-layer-hystrix

REST Layer Hystrix storage handler wrapper
Go
3
star
55

rrdpoller

Easily query and perform threshold tests on RRD files data
Perl
3
star
56

rrdcollect-remote

Collect rrdcollect output from several hosts to update local RRD files
Perl
2
star
57

SiriDailymotion

AssistantExtensions plugin to integrate Dailymotion to Siri on Jailbroken iPhone 4s
Objective-C
2
star
58

proxy

A simple HTTP explicit forward proxy http.Handler
Go
2
star
59

gcs-oauth2-boto-env-plugin

Google Storage auth2 plugin with support for passing service key via environment
Python
2
star
60

rs.github.com

1
star
61

obfu

Go
1
star