Skip to content

How to have same format when writing to file as well as terminal? #1069

Closed
@kaushikchaubal

Description

@kaushikchaubal

Hi,

I am writing an application where I want my logger to do 3 things (and how I :

  1. Have different level of logging ✅
  2. Includes timestamp and filename ✅
  3. Ability to write to file as well as to terminal ⚠️

I am looking for guidance for point 3. As of now, this is what i am doing to 'hack' around this feature:

logger := log.New()

logFile, err := os.OpenFile("logs.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
    panic(fmt.Sprintf("[Error]: %s", err))
}

mw := io.MultiWriter(os.Stdout, logFile)
logger.SetOutput(mw)

logger.SetFormatter(&log.TextFormatter{
    FullTimestamp: true,
    ForceColors:   true,
})

logger.Debug("Hello from Debug")
logger.Info("Hello from info")

This has the following outputs:

  1. Terminal:
INFO[2019-11-18T14:19:26Z] Hello from info                              
WARN[2019-11-18T14:19:26Z] Hello from warn 
  1. File
 �[36mINFO�[0m[2019-11-18T14:19:26Z] Hello from info                              
�[33mWARN�[0m[2019-11-18T14:19:26Z] Hello from warn  

Any ideas how I can make the File output look exactly the same as the Terminal one?

Note: I looked at #784 (which is also referenced in #888 and #780) but #784 changes the formatting to JSON (which is not what I am looking for)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions