Skip to content

Commit

Permalink
💥 Update Option names
Browse files Browse the repository at this point in the history
  • Loading branch information
nkmr-jp committed Jan 14, 2022
1 parent f0ebbca commit 944ea75
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 76 deletions.
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ pr:
@echo "${GREEN}# CREATE PULL REQUEST ${RESET}"
git commit --allow-empty -m ":tada: The first commit in $(B)"
gh pr create -a @me -t "[PR] $(T)" -B develop
gh pr view --web
gh pr view --web

doc:
@echo "open in web browser http://localhost:6060"
@godoc -http=:6060
59 changes: 47 additions & 12 deletions zl/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package zl_test

import (
"fmt"
"log"
"os"
"testing"
"time"

"github.com/nkmr-jp/zap-lightning/zl"
Expand All @@ -15,23 +17,56 @@ var (
srcRootDir string // srcRootDir set from cli.
)

func TestMain(m *testing.M) {
if err := os.RemoveAll("./log"); err != nil {
log.Fatal(err)
}
m.Run()
}

func Example() {
// Set Options
zl.SetLogLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetOutput(zl.PrettyOutput) // Default. it's recommended for develop environment.

// Initialize
zl.Init()
defer zl.Sync() // flush log buffer
zl.SyncWhenStop() // flush log buffer. when interrupt or terminated.

// Logs
zl.Info("USER_INFO", zap.String("name", "Alice"), zap.Int("age", 20))
// Write Logs
fmt.Println("Console:")
zl.Info("USER_INFO", zap.String("user_name", "Alice"), zap.Int("user_age", 20)) // can use zap fields.
err := fmt.Errorf("error message")
zl.Error("ERROR_MESSAGE", err) // error level log must with error message.
zl.Debug("DEBUG_MESSAGE")
zl.Warn("WARN_MESSAGE")
zl.WarnErr("WARN_MESSAGE_WITH_ERROR", err) // warn level log with error message.
zl.Info("DISPLAY_TO_CONSOLE", zl.Console("display to console"))
zl.Warn("WARN_MESSAGE", zap.Error(err)) // warn level log with error message.
zl.WarnErr("WARN_MESSAGE_WITH_ERROR", err) // same to above.
zl.Info("DISPLAY_TO_CONSOLE", zl.Console("display to console when output type is pretty"))

fmt.Println("\nFile:")
app, _ := os.ReadFile("./log/app.jsonl")
fmt.Println(string(app))

// Example output:
// Colored Simple Log
//
// 2022/01/14 12:01:52 zl.go:37: INFO INIT_LOGGER: logLevel: DEBUG, fileName: ./log/app.jsonl, outputType: Pretty
// 2022/01/14 12:01:52 example_test.go:28: INFO USER_INFO
// 2022/01/14 12:01:52 example_test.go:30: ERROR ERROR_MESSAGE: error message
// 2022/01/14 12:01:52 example_test.go:31: DEBUG DEBUG_MESSAGE
// 2022/01/14 12:01:52 example_test.go:32: WARN WARN_MESSAGE
// 2022/01/14 12:01:52 example_test.go:33: WARN WARN_MESSAGE_WITH_ERROR: error message
// 2022/01/14 12:01:52 example_test.go:34: INFO DISPLAY_TO_CONSOLE: display to console
// 2022/01/14 12:01:52 zl.go:89: INFO FLUSH_LOG_BUFFER
//
// {"level":"INFO","time":"2022-01-14T12:16:03.274814+09:00","caller":"zl/zl.go:37","function":"github.com/nkmr-jp/zap-lightning/zl.Init.func1","message":"INIT_LOGGER","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local","console":"logLevel: DEBUG, fileName: ./log/app.jsonl, outputType: Pretty"}
// {"level":"INFO","time":"2022-01-14T12:16:03.27503+09:00","caller":"zl/example_test.go:28","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"USER_INFO","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local","name":"Alice","age":20}
// {"level":"ERROR","time":"2022-01-14T12:16:03.275073+09:00","caller":"zl/example_test.go:30","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"ERROR_MESSAGE","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local","error":"error message","stacktrace":"github.com/nkmr-jp/zap-lightning/zl_test.Example\n\t/Users/nkmr/ghq/github.com/nkmr-jp/zap-lightning/zl/example_test.go:30\ntesting.runExample\n\t/Users/nkmr/.anyenv/envs/goenv/versions/1.17.5/src/testing/run_example.go:64\ntesting.runExamples\n\t/Users/nkmr/.anyenv/envs/goenv/versions/1.17.5/src/testing/example.go:44\ntesting.(*M).Run\n\t/Users/nkmr/.anyenv/envs/goenv/versions/1.17.5/src/testing/testing.go:1505\nmain.main\n\t_testmain.go:49\nruntime.main\n\t/Users/nkmr/.anyenv/envs/goenv/versions/1.17.5/src/runtime/proc.go:255"}
// {"level":"DEBUG","time":"2022-01-14T12:16:03.275159+09:00","caller":"zl/example_test.go:31","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"DEBUG_MESSAGE","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local"}
// {"level":"WARN","time":"2022-01-14T12:16:03.275186+09:00","caller":"zl/example_test.go:32","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"WARN_MESSAGE","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local"}
// {"level":"WARN","time":"2022-01-14T12:16:03.275208+09:00","caller":"zl/example_test.go:33","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"WARN_MESSAGE_WITH_ERROR","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local","error":"error message"}
// {"level":"INFO","time":"2022-01-14T12:16:03.275233+09:00","caller":"zl/example_test.go:34","function":"github.com/nkmr-jp/zap-lightning/zl_test.Example","message":"DISPLAY_TO_CONSOLE","version":"f0ebbca","hostname":"nkmrnoMacBook-Pro.local","console":"display to console"}

// Output:
}
Expand All @@ -42,7 +77,7 @@ func ExampleSetVersion() {
srcRootDir, _ = os.Getwd()

// Set Options
zl.SetLogLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetVersion(version)
zl.SetFileName(fmt.Sprintf("./log/app_%s.jsonl", zl.GetVersion()))
zl.SetRepositoryCallerEncoder(
Expand All @@ -60,10 +95,10 @@ func ExampleSetVersion() {
// Output:
}

func ExampleSetOutputType() {
func ExampleSetOutput() {
// Set options
zl.SetLogLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetOutputType(zl.OutputTypeConsole)
zl.SetLevel(zapcore.DebugLevel) // Default is InfoLevel
zl.SetOutput(zl.ConsoleOutput)

// Initialize
zl.Init()
Expand All @@ -73,9 +108,9 @@ func ExampleSetOutputType() {
// Logs
zl.Info("USER_INFO", zl.Console("message"))

// Output:
// Example output:
// {"level":"INFO","ts":"2022-01-14T06:43:03.345143+09:00","caller":"zl/zl.go:36","function":"github.com/nkmr-jp/zap-lightning/zl.Init.func1","msg":"INIT_LOGGER","version":"dd90b59","hostname":"nkmrnoMacBook-Pro.local","console":"logLevel: DEBUG, fileName: , outputType: Console"}
// {"level":"INFO","ts":"2022-01-14T06:43:03.345329+09:00","recaller":"zap-lightning/example_test.go:74","function":"github.com/nkmr-jp/zap-lightning_test.ExampleSetOutputType","msg":"USER_INFO","version":"dd90b59","hostname":"nkmrnoMacBook-Pro.local","console":"message"}
// {"level":"INFO","ts":"2022-01-14T06:43:03.345329+09:00","caller":"zap-lightning/example_test.go:74","function":"github.com/nkmr-jp/zap-lightning_test.ExampleSetOutputType","msg":"USER_INFO","version":"dd90b59","hostname":"nkmrnoMacBook-Pro.local","console":"message"}
// {"level":"INFO","ts":"2022-01-14T06:43:03.345341+09:00","caller":"zl/logger.go:67","function":"github.com/nkmr-jp/zap-lightning/zl.Sync","msg":"FLUSH_LOG_BUFFER","version":"dd90b59","hostname":"nkmrnoMacBook-Pro.local"}
}

Expand Down
38 changes: 1 addition & 37 deletions zl/logger.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
package zl

import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"

"go.uber.org/zap"
)
Expand All @@ -15,7 +10,7 @@ type Logger struct {
Fields []zap.Field
}

// New can additional default fields.
// New can add additional default fields.
// ex. Use this when you want to add a common value in the scope of a context, such as an API request.
func New(fields ...zap.Field) *Logger {
return &Logger{Fields: fields}
Expand Down Expand Up @@ -61,37 +56,6 @@ func (w *Logger) WarnErr(msg string, err error, fields ...zap.Field) {
loggerErr(msg, "WARN", err, fields).Warn(msg, fields...)
}

// Sync logger of Zap's Sync.
// Note: If log output to console. error will occur (See: https://github.com/uber-go/zap/issues/880 )
func Sync() {
Info("FLUSH_LOG_BUFFER")
if err := zapLogger.Sync(); err != nil {
log.Println(err)
}
}

// SyncWhenStop flush log buffer. when interrupt or terminated.
func SyncWhenStop() {
c := make(chan os.Signal, 1)

go func() {
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
s := <-c

sigCode := 0
switch s.String() {
case "interrupt":
sigCode = 2
case "terminated":
sigCode = 15
}

Info(fmt.Sprintf("GOT_SIGNAL_%v", strings.ToUpper(s.String())))
Sync() // flush log buffer
os.Exit(128 + sigCode)
}()
}

// Debug is Logger of Zap's Debug.
// Outputs a short log to the console. Detailed json log output to log file.
func Debug(msg string, fields ...zap.Field) {
Expand Down
40 changes: 20 additions & 20 deletions zl/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,53 +8,53 @@ import (
"go.uber.org/zap/zapcore"
)

type OutputType int
type Output int

const (
// OutputTypePretty writes the colored simple log to console,
// PrettyOutput writes the colored simple log to console,
// and writes json structured detail log to file.
// it is Default setting.
// Recommended for Develop Environment.
OutputTypePretty OutputType = iota
PrettyOutput Output = iota

// OutputTypeConsoleAndFile writes json structured log to console and file.
// ConsoleAndFileOutput writes json structured log to console and file.
// Recommended for Develop Environment.
OutputTypeConsoleAndFile
ConsoleAndFileOutput

// OutputTypeConsole writes json structured log to console.
// ConsoleOutput writes json structured log to console.
// Recommended for Develop and Production Environment.
OutputTypeConsole
ConsoleOutput

// OutputTypeFile writes json structured log to file.
// FileOutput writes json structured log to file.
// Recommended for Develop and Production Environment.
OutputTypeFile
FileOutput
)

var outputTypeStrings = [4]string{
var outputStrings = [4]string{
"Pretty",
"ConsoleAndFile",
"Console",
"File",
}

func (o OutputType) String() string {
return outputTypeStrings[o]
func (o Output) String() string {
return outputStrings[o]
}

func SetOutputType(option OutputType) {
func SetOutput(option Output) {
outputType = option
}

// SetOutputTypeByString outputTypeStr can use (SimpleConsoleAndFile, ConsoleAndFile, Console, File).
// SetOutputTypeByString can use (SimpleConsoleAndFile, ConsoleAndFile, Console, File).
func SetOutputTypeByString(outputTypeStr string) {
var output OutputType
var output Output
if outputTypeStr == "" {
SetOutputType(output)
SetOutput(output)
return
}
for i, i2 := range outputTypeStrings {
for i, i2 := range outputStrings {
if outputTypeStr == i2 {
SetOutputType(OutputType(i))
SetOutput(Output(i))
return
}
}
Expand All @@ -64,7 +64,7 @@ func SetOutputTypeByString(outputTypeStr string) {
)
}

func SetLogLevel(option zapcore.Level) {
func SetLevel(option zapcore.Level) {
logLevel = option
}

Expand All @@ -75,7 +75,7 @@ func SetLogLevelByString(levelStr string) {
if err != nil {
log.Fatalf("%s is invalid level. can use (DEBUG,INFO,WARN,ERROR,FATAL)", levelStr)
}
SetLogLevel(level)
SetLevel(level)
}

// SetRepositoryCallerEncoder is set CallerEncoder. it set caller's source code's URL of the Repository that called.
Expand Down
4 changes: 2 additions & 2 deletions zl/prettylog.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

func prettyLog(msg, levelStr string, fields []zap.Field) {
if outputType != OutputTypePretty {
if outputType != PrettyOutput {
return
}
if !checkLevel(levelStr) {
Expand All @@ -35,7 +35,7 @@ func prettyLog(msg, levelStr string, fields []zap.Field) {
}

func prettyLogWithError(msg string, levelStr string, err error, fields []zap.Field) {
if outputType != OutputTypePretty {
if outputType != PrettyOutput {
return
}
if !checkLevel(levelStr) {
Expand Down
42 changes: 38 additions & 4 deletions zl/zl.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// Package zl provides zap based advanced logging features, and it's easy to use.
package zl

import (
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand All @@ -19,7 +22,7 @@ const (
var (
once sync.Once
zapLogger *zap.Logger
outputType OutputType
outputType Output
version string
logLevel zapcore.Level // Default is InfoLevel
callerEncoder zapcore.CallerEncoder
Expand Down Expand Up @@ -80,6 +83,37 @@ func GetVersion() string {
return "undefined"
}

// Sync logger of Zap's Sync.
// Note: If log output to console. error will occur (See: https://github.com/uber-go/zap/issues/880 )
func Sync() {
Info("FLUSH_LOG_BUFFER")
if err := zapLogger.Sync(); err != nil {
log.Println(err)
}
}

// SyncWhenStop flush log buffer. when interrupt or terminated.
func SyncWhenStop() {
c := make(chan os.Signal, 1)

go func() {
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
s := <-c

sigCode := 0
switch s.String() {
case "interrupt":
sigCode = 2
case "terminated":
sigCode = 15
}

Info(fmt.Sprintf("GOT_SIGNAL_%v", strings.ToUpper(s.String())))
Sync() // flush log buffer
os.Exit(128 + sigCode)
}()
}

func getHost() *string {
ret, err := os.Hostname()
if err != nil {
Expand All @@ -98,11 +132,11 @@ func getCallerEncoder() zapcore.CallerEncoder {

func getSyncers() (syncers []zapcore.WriteSyncer) {
switch outputType {
case OutputTypePretty, OutputTypeFile:
case PrettyOutput, FileOutput:
syncers = append(syncers, zapcore.AddSync(newRotator()))
case OutputTypeConsoleAndFile:
case ConsoleAndFileOutput:
syncers = append(syncers, zapcore.AddSync(os.Stderr), zapcore.AddSync(newRotator()))
case OutputTypeConsole:
case ConsoleOutput:
syncers = append(syncers, zapcore.AddSync(os.Stderr))
}
return
Expand Down

0 comments on commit 944ea75

Please sign in to comment.