phuslu / log

Fastest structured logging
MIT License
672 stars 44 forks source link

MultiWriter based on io.Writer #32

Closed ogimenezb closed 3 years ago

ogimenezb commented 3 years ago

Sometimes I need to write to different outputs with a selected level. For example, given a Debug level I would like to be able to write to console, log file and syslog.

Have tried io.MultiWriter but ConsoleWriter does not implement io.Writer method.

Alternatively we could implement something like https://github.com/rs/zerolog/blob/117cb53bc66413d9a810ebed32383e53416347e3/writer.go#L88

I have tried several things and the only option I see is MultiWriter but it's level based not io.Writer based.

Any suggestions?

phuslu commented 3 years ago

Can use log.IOWriter to wrap your writer.

Or

Just copy multi.go to your project then modify it.

ogimenezb commented 3 years ago

The best way would be to change multi.go I ca make changes if you like them.

How about adding in multi.go

type CustomMultiWriter struct {
    W Writer
    L Level
}

// MultiWriter is an Writer that log to different writers by different levels
type MultiWriter struct {
    // InfoWriter specifies all the level logs writes to
    InfoWriter Writer

    // WarnWriter specifies the level greater than or equal to WarnLevel writes to
    WarnWriter Writer

    // WarnWriter specifies the level greater than or equal to ErrorLevel writes to
    ErrorWriter Writer

    // ConsoleWriter specifies the console writer
    ConsoleWriter Writer

    // ConsoleLevel specifies the level greater than or equal to it also writes to
    ConsoleLevel Level

    CustomWriter []CustomMultiWriter
}

Then we can use range to WriteEntry.

This would not break API and add any type of configuration you want. (not great at naming things...)

phuslu commented 3 years ago

indeed log.MultiWriter is to simulate glog multi output destination, not stdlib io.MultiWriter. I'd like to keep it simple. For you case/requirment, I'd write a example in README.md.

phuslu commented 3 years ago

A example here, https://play.golang.org/p/bwo03SW0B3l Also added to readme https://github.com/phuslu/log#multiple-io-writer

ogimenezb commented 3 years ago

My case is a little different: I want to also write on Console.

Here is the same implementation, just changed to use log.Writer

As a benefit I can use all your xxxWriter implementations.

https://play.golang.org/p/zWwka4CS80b

phuslu commented 3 years ago

Understood.

A Pull Request is very welcome. But if you're a bit busy, I also happy copy & modify your code to repo.

ogimenezb commented 3 years ago

I have to go out now, if you can wait until this afternoon I'm game. UTC+2

phuslu commented 3 years ago

Sure, happy to depends on you.