|
| 1 | +package lg |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "os" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "go.uber.org/zap" |
| 9 | + "go.uber.org/zap/zapcore" |
| 10 | + |
| 11 | + "github.com/Shopify/sarama" |
| 12 | +) |
| 13 | + |
| 14 | +// kafkaConfig contains information |
| 15 | +type kafkaConfig struct { |
| 16 | + Hosts string |
| 17 | + Topic string |
| 18 | +} |
| 19 | + |
| 20 | +// write2Kafka is used for sending logs to kafka. |
| 21 | +type write2Kafka struct { |
| 22 | + config *kafkaConfig |
| 23 | + syncProducer sarama.SyncProducer |
| 24 | +} |
| 25 | + |
| 26 | +func (w *write2Kafka) Write(b []byte) (n int, err error) { |
| 27 | + if _, _, err = w.syncProducer.SendMessage(&sarama.ProducerMessage{ |
| 28 | + Topic: w.config.Topic, |
| 29 | + Value: sarama.ByteEncoder(b), |
| 30 | + }); err != nil { |
| 31 | + return |
| 32 | + } |
| 33 | + n = len(b) |
| 34 | + return |
| 35 | +} |
| 36 | + |
| 37 | +func newLog2Kafka(cfg *kafkaConfig) (*write2Kafka, error) { |
| 38 | + config := sarama.NewConfig() |
| 39 | + // SyncProducer |
| 40 | + config.Producer.RequiredAcks = sarama.WaitForLocal // Only wait for the leader to ack |
| 41 | + config.Producer.Compression = sarama.CompressionSnappy // Compress messages |
| 42 | + // Producer.Return.Successes must be true to be used in a SyncProducer |
| 43 | + config.Producer.Return.Successes = true |
| 44 | + |
| 45 | + var brokerList []string |
| 46 | + for _, broker := range strings.Split(cfg.Hosts, ",") { |
| 47 | + if strings.Index(broker, ":") == -1 { |
| 48 | + broker += ":9092" |
| 49 | + } |
| 50 | + brokerList = append(brokerList, broker) |
| 51 | + } |
| 52 | + |
| 53 | + var producer sarama.SyncProducer |
| 54 | + var err error |
| 55 | + if producer, err = sarama.NewSyncProducer(brokerList, config); err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + |
| 59 | + return &write2Kafka{config: cfg, syncProducer: producer}, nil |
| 60 | +} |
| 61 | + |
| 62 | +// Init initializes log by input parameters |
| 63 | +// lvl - global log level: Debug(-1), Info(0), Warn(1), Error(2), DPanic(3), Panic(4), Fatal(5) |
| 64 | +// timeFormat - custom time format for logger of empty string to use default |
| 65 | +func InitOnlyKafka(lvl int, project, kafkaTopic, brokers string) (err error) { |
| 66 | + onceInit.Do(func() { |
| 67 | + globalLevel := zapcore.Level(lvl) |
| 68 | + |
| 69 | + KafkaPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { |
| 70 | + return lvl >= globalLevel |
| 71 | + }) |
| 72 | + var ws io.Writer |
| 73 | + if ws, err = newLog2Kafka(&kafkaConfig{Hosts: brokers, Topic: kafkaTopic}); err != nil { |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + // Configure console output. |
| 78 | + cfg := zap.NewProductionEncoderConfig() |
| 79 | + if len(TimeFormat) > 0 { |
| 80 | + cfg.TimeKey = "tsp" |
| 81 | + cfg.EncodeTime = customTimeEncoder |
| 82 | + } |
| 83 | + |
| 84 | + // Optimize the Kafka output for machine consumption and the console output |
| 85 | + // for human operators. |
| 86 | + core := zapcore.NewTee(zapcore.NewCore(zapcore.NewJSONEncoder(cfg), zapcore.Lock(zapcore.AddSync(ws)), KafkaPriority)) |
| 87 | + |
| 88 | + // ErrorLevel 堆栈跟踪 |
| 89 | + stackTrace := zap.AddStacktrace(zap.ErrorLevel) |
| 90 | + // 设置初始化字段 |
| 91 | + fields := zap.Fields(zap.Object("info", &commonInfo{project, getHostName()})) |
| 92 | + |
| 93 | + // From a zapcore.Core, it's easy to construct a Logger. |
| 94 | + APPLog = zap.New(core, fields, stackTrace) |
| 95 | + }) |
| 96 | + return err |
| 97 | +} |
| 98 | + |
| 99 | +// Init initializes log by input parameters |
| 100 | +// lvl - global log level: Debug(-1), Info(0), Warn(1), Error(2), DPanic(3), Panic(4), Fatal(5) |
| 101 | +// timeFormat - custom time format for logger of empty string to use default |
| 102 | +func InitWithKafka(lvl int, project, kafkaTopic, brokers string) (err error) { |
| 103 | + onceInit.Do(func() { |
| 104 | + // First, define our level-handling logic. |
| 105 | + globalLevel := zapcore.Level(lvl) |
| 106 | + // High-priority output should also go to standard error, and low-priority |
| 107 | + // output should also go to standard out. |
| 108 | + // It is usefull for Kubernetes deployment. |
| 109 | + // Kubernetes interprets os.Stdout log items as INFO and os.Stderr log items |
| 110 | + // as ERROR by default. |
| 111 | + highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { |
| 112 | + return lvl >= zapcore.ErrorLevel |
| 113 | + }) |
| 114 | + lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { |
| 115 | + return lvl >= globalLevel && lvl < zapcore.ErrorLevel |
| 116 | + }) |
| 117 | + |
| 118 | + KafkaPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { |
| 119 | + return lvl >= globalLevel |
| 120 | + }) |
| 121 | + // Assume that we have clients for two Kafka topics. The clients implement |
| 122 | + // zapcore.WriteSyncer and are safe for concurrent use. (If they only |
| 123 | + // implement io.Writer, we can use zapcore.AddSync to add a no-op Sync |
| 124 | + // method. If they're not safe for concurrent use, we can add a protecting |
| 125 | + // mutex with zapcore.Lock.) |
| 126 | + var ws io.Writer |
| 127 | + if ws, err = newLog2Kafka(&kafkaConfig{Hosts: brokers, Topic: kafkaTopic}); err != nil { |
| 128 | + return |
| 129 | + } |
| 130 | + |
| 131 | + // Configure console output. |
| 132 | + cfg := zap.NewProductionEncoderConfig() |
| 133 | + if len(TimeFormat) > 0 { |
| 134 | + cfg.TimeKey = "tsp" |
| 135 | + cfg.EncodeTime = customTimeEncoder |
| 136 | + } |
| 137 | + |
| 138 | + // Optimize the Kafka output for machine consumption and the console output |
| 139 | + // for human operators. |
| 140 | + kafkaEncoder := zapcore.NewJSONEncoder(cfg) |
| 141 | + consoleEncoder := zapcore.NewJSONEncoder(cfg) |
| 142 | + // Join the outputs, encoders, and level-handling functions into |
| 143 | + // zapcore.Cores, then tee the four cores together. |
| 144 | + core := zapcore.NewTee( |
| 145 | + zapcore.NewCore(kafkaEncoder, zapcore.Lock(zapcore.AddSync(ws)), KafkaPriority), |
| 146 | + // 同时写一份到标准输出 |
| 147 | + zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), lowPriority), |
| 148 | + zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stderr), highPriority), |
| 149 | + ) |
| 150 | + |
| 151 | + // ErrorLevel 堆栈跟踪 |
| 152 | + stackTrace := zap.AddStacktrace(zap.ErrorLevel) |
| 153 | + // 设置初始化字段 |
| 154 | + fields := zap.Fields(zap.Object("info", &commonInfo{project, getHostName()})) |
| 155 | + |
| 156 | + // From a zapcore.Core, it's easy to construct a Logger. |
| 157 | + APPLog = zap.New(core, fields, stackTrace) |
| 158 | + }) |
| 159 | + return err |
| 160 | +} |
0 commit comments