zmlog
generates the file which has MarshalLogObject method from struct.
go install github.com/muroon/zmlog/cmd/zmlog@latest
For example, there is a file target.go
that describes the struct for Log as follows.
type TargetLog struct {
ID int
Name string
Time time.Time
}
Run the command below,
zmlog -f target.go
And zmlog
generates a file target_zap_obj.go
with MarshalLogObject method.
// MarshalLogObject zapcore.ObjectMarshaler interface method
func (l *TargetLog) MarshalLogObject(enc zapcore.ObjectEncoder) error {
var err error
enc.AddInt("id", l.ID)
enc.AddString("name", l.Name)
enc.AddTime("time", l.Time)
return err
}
The key name for zapcore.ObjectEncoder
's method like AddInt or AddString... is basically the field name of the target struct with snake case.
However, as an exception, create a tag with key: "key name"
in the field of the struct.
In the example below, it is originally enc.AddString("sessison_id", l.SessionID)
, but it becomes enc.AddString("sess_id", l.SessionID)
type TargetLog struct {
ID int
Name string
Time time.Time
SessionID string `key:"sess_id"` // custom key
}
func (l *TargetLog) MarshalLogObject(enc zapcore.ObjectEncoder) error {
var err error
enc.AddInt("id", l.ID)
enc.AddString("name", l.Name)
enc.AddTime("time", l.Time)
enc.AddString("sess_id", l.SessionID) // not be `sessison_id`
return err
}