NewFileLogger returns a new FileLogger from a config.
(ctx context.Context, config *FileLoggerConfig, level LogLevel, name string, logFilePath string, minAge int, defaultMaxAgeOverride *int, buffer *strings.Builder)
| 90 | |
| 91 | // NewFileLogger returns a new FileLogger from a config. |
| 92 | func NewFileLogger(ctx context.Context, config *FileLoggerConfig, level LogLevel, name string, logFilePath string, minAge int, defaultMaxAgeOverride *int, buffer *strings.Builder) (*FileLogger, error) { |
| 93 | if config == nil { |
| 94 | config = &FileLoggerConfig{} |
| 95 | } |
| 96 | |
| 97 | cancelCtx, cancelFunc := context.WithCancel(ctx) |
| 98 | |
| 99 | // validate and set defaults |
| 100 | rotationDoneChan, err := config.init(cancelCtx, level, name, logFilePath, minAge, defaultMaxAgeOverride) |
| 101 | if err != nil { |
| 102 | cancelFunc() |
| 103 | return nil, err |
| 104 | } |
| 105 | |
| 106 | logger := &FileLogger{ |
| 107 | Enabled: AtomicBool{}, |
| 108 | level: level, |
| 109 | name: name, |
| 110 | output: config.Output, |
| 111 | logger: log.New(config.Output, "", 0), |
| 112 | config: *config, |
| 113 | closed: make(chan struct{}), |
| 114 | cancelFunc: cancelFunc, |
| 115 | rotationDoneChan: rotationDoneChan, |
| 116 | } |
| 117 | logger.Enabled.Set(*config.Enabled) |
| 118 | |
| 119 | if buffer != nil { |
| 120 | logger.buffer = *buffer |
| 121 | } |
| 122 | |
| 123 | // Only create the collateBuffer channel and worker if required. |
| 124 | if *config.CollationBufferSize > 1 { |
| 125 | logger.collateBuffer = make(chan string, *config.CollationBufferSize) |
| 126 | logger.flushChan = make(chan struct{}, 1) |
| 127 | logger.collateBufferWg = &sync.WaitGroup{} |
| 128 | |
| 129 | // Start up a single worker to consume messages from the buffer |
| 130 | go logCollationWorker(logger.closed, logger.collateBuffer, logger.flushChan, logger.collateBufferWg, logger.logger, *config.CollationBufferSize, fileLoggerCollateFlushTimeout) |
| 131 | } |
| 132 | |
| 133 | return logger, nil |
| 134 | } |
| 135 | |
| 136 | func (l *FileLogger) FlushBufferToLog() { |
| 137 | // Need to clear hanging new line to avoid empty line |