InitFromConfig initializes a Logrus instance from config options.
(c Config, filename string)
| 40 | |
| 41 | // InitFromConfig initializes a Logrus instance from config options. |
| 42 | func InitFromConfig(c Config, filename string) error { |
| 43 | exe, err := os.Executable() |
| 44 | var path string |
| 45 | if err != nil { |
| 46 | path = filepath.Join(os.Getenv("PROGRAMFILES"), "Fibratus", "Logs") |
| 47 | } else { |
| 48 | path = filepath.Join(filepath.Dir(exe), "..", "Logs") |
| 49 | } |
| 50 | if c.Path != "" { |
| 51 | path = c.Path |
| 52 | } |
| 53 | if path == "" { |
| 54 | return errors.New("got an empty logs directory path. Please make sure Fibratus is installed properly") |
| 55 | } |
| 56 | _, err = os.Stat(path) |
| 57 | if err != nil { |
| 58 | // let's create the logs directory since it doesn't exist, even though |
| 59 | // this should rarely happen because Fibratus installer already creates |
| 60 | // the logs directory |
| 61 | if err := os.MkdirAll(path, os.ModePerm); err != nil { |
| 62 | return fmt.Errorf("unable to create the %s logs directory: %v", path, err) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | file := filepath.Join(path, filename) |
| 67 | |
| 68 | // setup log formatter |
| 69 | var formatter logrus.Formatter |
| 70 | switch c.Formatter { |
| 71 | case "json": |
| 72 | formatter = &logrus.JSONFormatter{} |
| 73 | case "text": |
| 74 | formatter = &logrus.TextFormatter{DisableQuote: true} |
| 75 | default: |
| 76 | formatter = &logrus.JSONFormatter{} |
| 77 | } |
| 78 | logrus.SetFormatter(formatter) |
| 79 | |
| 80 | level, err := logrus.ParseLevel(c.Level) |
| 81 | if err != nil { |
| 82 | return err |
| 83 | } |
| 84 | logrus.SetLevel(level) |
| 85 | |
| 86 | // disable writing to stdout |
| 87 | if !c.LogStdout { |
| 88 | logrus.SetOutput(io.Discard) |
| 89 | } |
| 90 | |
| 91 | // initialize log rotate hook |
| 92 | rhook, err := rotate.NewHook(rotate.Config{ |
| 93 | MaxAge: c.MaxAge, |
| 94 | MaxBackups: c.MaxBackups, |
| 95 | MaxSize: c.MaxSize, |
| 96 | Level: level, |
| 97 | Formatter: formatter, |
| 98 | Filename: file, |
| 99 | }) |