summaryrefslogtreecommitdiff
path: root/plugins/logger/plugin.go
blob: e1066cbaa49c77bf767faef5ab773d3d0da6f7a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package logger

import (
	endure "github.com/spiral/endure/pkg/container"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/plugins/config"
	"go.uber.org/zap"
)

// PluginName declares plugin name.
const PluginName = "logs"

// ZapLogger manages zap logger.
type ZapLogger struct {
	base     *zap.Logger
	cfg      *Config
	channels ChannelConfig
}

// Init logger service.
func (z *ZapLogger) Init(cfg config.Configurer) error {
	const op = errors.Op("config_plugin_init")
	var err error
	// if not configured, configure with default params
	if !cfg.Has(PluginName) {
		z.cfg = &Config{}
		z.cfg.InitDefault()

		z.base, err = z.cfg.BuildLogger()
		if err != nil {
			return errors.E(op, errors.Disabled, err)
		}

		return nil
	}

	err = cfg.UnmarshalKey(PluginName, &z.cfg)
	if err != nil {
		return errors.E(op, errors.Disabled, err)
	}

	err = cfg.UnmarshalKey(PluginName, &z.channels)
	if err != nil {
		return errors.E(op, errors.Disabled, err)
	}

	z.base, err = z.cfg.BuildLogger()
	if err != nil {
		return errors.E(op, errors.Disabled, err)
	}
	return nil
}

// DefaultLogger returns default logger.
func (z *ZapLogger) DefaultLogger() (Logger, error) {
	return NewZapAdapter(z.base), nil
}

// NamedLogger returns logger dedicated to the specific channel. Similar to Named() but also reads the core params.
func (z *ZapLogger) NamedLogger(name string) (Logger, error) {
	if cfg, ok := z.channels.Channels[name]; ok {
		l, err := cfg.BuildLogger()
		if err != nil {
			return nil, err
		}
		return NewZapAdapter(l.Named(name)), nil
	}

	return NewZapAdapter(z.base.Named(name)), nil
}

// ServiceLogger returns logger dedicated to the specific channel. Similar to Named() but also reads the core params.
func (z *ZapLogger) ServiceLogger(n endure.Named) (Logger, error) {
	return z.NamedLogger(n.Name())
}

// Provides declares factory methods.
func (z *ZapLogger) Provides() []interface{} {
	return []interface{}{
		z.ServiceLogger,
		z.DefaultLogger,
	}
}