Git Product home page Git Product logo

logger's Introduction

logger

Logger is a simple cross platform Go logging library for Windows, Linux, FreeBSD, and macOS, it can log to the Windows event log, Linux/macOS syslog, and an io.Writer.

This is not an official Google product.

Usage

Set up the default logger to log the system log (event log or syslog) and a file, include a flag to turn up verbosity:

import (
  "flag"
  "os"

  "github.com/google/logger"
)

const logPath = "/some/location/example.log"

var verbose = flag.Bool("verbose", false, "print info level logs to stdout")

func main() {
  flag.Parse()

  lf, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
  if err != nil {
    logger.Fatalf("Failed to open log file: %v", err)
  }
  defer lf.Close()

  defer logger.Init("LoggerExample", *verbose, true, lf).Close()

  logger.Info("I'm about to do something!")
  if err := doSomething(); err != nil {
    logger.Errorf("Error running doSomething: %v", err)
  }
}

The Init function returns a logger so you can setup multiple instances if you wish, only the first call to Init will set the default logger:

lf, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
  logger.Fatalf("Failed to open log file: %v", err)
}
defer lf.Close()

// Log to system log and a log file, Info logs don't write to stdout.
loggerOne := logger.Init("LoggerExample", false, true, lf)
defer loggerOne.Close()
// Don't to system log or a log file, Info logs write to stdout..
loggerTwo := logger.Init("LoggerExample", true, false, ioutil.Discard)
defer loggerTwo.Close()

loggerOne.Info("This will log to the log file and the system log")
loggerTwo.Info("This will only log to stdout")
logger.Info("This is the same as using loggerOne")

Custom Format

Code Example
logger.SetFlags(log.Ldate) ERROR: 2018/11/11 Error running Foobar: message
logger.SetFlags(log.Ltime) ERROR: 09:42:45 Error running Foobar: message
logger.SetFlags(log.Lmicroseconds) ERROR: 09:42:50.776015 Error running Foobar: message
logger.SetFlags(log.Llongfile) ERROR: /src/main.go:31: Error running Foobar: message
logger.SetFlags(log.Lshortfile) ERROR: main.go:31: Error running Foobar: message
logger.SetFlags(log.LUTC) ERROR: Error running Foobar: message
logger.SetFlags(log.LstdFlags) ERROR: 2018/11/11 09:43:12 Error running Foobar: message
func main() {
    lf, err := os.OpenFile(logPath, …, 0660)
    defer logger.Init("foo", *verbose, true, lf).Close()
    logger.SetFlags(log.LstdFlags)
}

More info: https://golang.org/pkg/log/#pkg-constants

logger's People

Contributors

adjackura avatar alexherrero avatar ashi009 avatar cixtor avatar dependabot[bot] avatar mike-seagull avatar pkern avatar schachmat avatar seanburford avatar thorduri avatar toneill818 avatar zchee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logger's Issues

Multiple output files doesn't use the correct "SetFlags"

I'm using the below configuration where multiple files are in use for writing logs. However with the SetFlags options in place, I noticed that only first file adhere to the settings. Rest of the files fall back to generic option where the "code line numbers" are being printed.

Code Snippet (Initializing files and logger):

lf2, err := os.OpenFile("log/server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
	logger.Fatalf("Failed to open log file: %v", err)
}
defer lf2.Close()
lf3, err := os.OpenFile("log/auth.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
	logger.Fatalf("Failed to open log file: %v", err)
}
defer lf3.Close()
glogger = logger.Init("Websockets Logger", false, false, lf)
defer glogger.Close()

Ologger = logger.Init("General Logger", false, false, lf2)
defer Ologger.Close()

userlogger = logger.Init("Authentication Logger", false, false, lf3)
defer userlogger.Close()

Code Snippet: (Initializing logger flags)
logger.SetFlags(log.LstdFlags | log.LUTC)

Not working inside docker image

Logger library is working as expected in Linux (Ubuntu 18.04 LTS) and in Mac os but
when I am running it in docker having alpine Linux as a base image, it is stuck at

logger.Init("foo", *verbose, true, lf)

I am using its latest version by downloading it using go get github.com/google/logger

It's blocking the entire application as the func logger.Init() is not returning.

My implementation:

func mustInitLogger() *logger.Logger {
	fmt.Printf("initializing x-microservice application log\n")
	lf, err  := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		panic(err)
	}
	fmt.Printf("log file created, initializing x-microservice logger instance\n")
	logr := logger.Init("x-microservice", true, true, lf)
	logger.SetFlags(log.LstdFlags)
	fmt.Printf("log initialization done\n")
	return logr
}

Update:

When I switched to version v1.0.1, I get this error:

unix syslog delivery error

custom logger format output

output by default

INFO : 2018/09/26 06:00:06.607994 test.go:25: hello

how to remove date info and test.go:25 just need "hello"

Allow setting log depth

Log depth is currently fixed for inferring logging file and line number, which is not very handy in the case where a helper function wants to log as the caller. For instance:

func retry(fn func() error) error {
  for attempt := 0; ; {
    if attempt > 0 {
      time.Sleep(backoff(attempt))
      logger.InfoDepth(1, fmt.Sprintf("Retry %d", attempt)) // logging from this line doesn't correct reflect the context.
    }
    err := fn()
    if err == nil {
       return nil
    }
    if !isRetryable(err) {
       return err
    }
    logger.InfoDepth(1, fmt.Sprintf("Got retryable error: %v", err)) // ditto
  }
  return nil
}

if err := retry(func() error {
  httpClient.Do(...)
}); err != nil {
  // ..
}

Allow setting log flags

Currently all logs generated by the logger package are fixed with the following format:
INFO : 2018/03/08 14:40:40.643151 filename.go:100: some message...

It would be great to be able to define the flags that are passed to the log package when initializing the logger instance, in order to define the format of the logged messages.

how to prevent ERROR messages going to stdout ?

well i saw no way to set a flag or other option to prevent ERROR messages printing in console.
I would like all logger messages to be only in a file

verbose false and system false did not help

Support for Windows EventIDs

Logger is useful for handling logging to Windows EventLog, but unfortunately the event IDs used by logger are hardcoded and not configurable by the user. It would be greatly preferable to have a way to set a unique event ID for each log message, so logs that are aggregated can be filtered effectively.

undefined: setup

Getting:
google/logger/logger.go:81:21: undefined: setup
when running go get github.com/google/logger

go version go1.11.4 linux/amd64

File already be closed

When I try to run the demo in the README.md, I found a little mistake.
If I replace defer lf.Close() with

defer func() {  
    if err := lf.Close(); err != nil {  
        panic(err)
    }  
}  

I will get err msg like this: file already be closed!

Add Semver.

Please add semantic versioning so that go mod doesnt points to an arbitrary commit in master branch.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.