Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect log format flag/config for stdout logs #1770

Merged
merged 6 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion internal/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ import (
// gcsfuse.log in case of GCSFuse.
const ProgrammeName string = "gcsfuse"
ashmeenkaur marked this conversation as resolved.
Show resolved Hide resolved
const GCSFuseInBackgroundMode string = "GCSFUSE_IN_BACKGROUND_MODE"
const jsonFormat string = "json"
const textFormat string = "text"
const defaultFormat string = jsonFormat

var (
defaultLoggerFactory *loggerFactory
Expand Down Expand Up @@ -98,12 +101,22 @@ func InitLogFile(logConfig config.LogConfig) error {
func init() {
defaultLoggerFactory = &loggerFactory{
file: nil,
format: defaultFormat,
level: config.INFO, // setting log level to INFO by default
logRotateConfig: config.DefaultLogRotateConfig(),
}
defaultLogger = defaultLoggerFactory.newLogger(config.INFO)
}

// SetLogFormat updates the log format of default logger.
func SetLogFormat(format string) {
if format == defaultLoggerFactory.format {
return
}
defaultLoggerFactory.format = format
ashmeenkaur marked this conversation as resolved.
Show resolved Hide resolved
defaultLogger = defaultLoggerFactory.newLogger(defaultLoggerFactory.level)
}

// Close closes the log file when necessary.
func Close() {
if f := defaultLoggerFactory.file; f != nil {
Expand Down Expand Up @@ -169,7 +182,7 @@ func (f *loggerFactory) newLogger(level config.LogSeverity) *slog.Logger {
}

func (f *loggerFactory) createJsonOrTextHandler(writer io.Writer, levelVar *slog.LevelVar, prefix string) slog.Handler {
if f.format == "text" {
if f.format == textFormat {
ashmeenkaur marked this conversation as resolved.
Show resolved Hide resolved
return slog.NewTextHandler(writer, getHandlerOptions(levelVar, prefix, f.format))
}
return slog.NewJSONHandler(writer, getHandlerOptions(levelVar, prefix, f.format))
Expand Down
59 changes: 51 additions & 8 deletions internal/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,21 @@ func init() { RegisterTestSuite(&LoggerTest{}) }
// Boilerplate
// //////////////////////////////////////////////////////////////////////

func redirectLogsToGivenBuffer(buf *bytes.Buffer, level config.LogSeverity) {
var programLevel = new(slog.LevelVar)
defaultLogger = slog.New(
defaultLoggerFactory.createJsonOrTextHandler(buf, programLevel, "TestLogs: "),
)
setLoggingLevel(level, programLevel)
}

// fetchLogOutputForSpecifiedSeverityLevel takes configured severity and
// functions that write logs as parameter and returns string array containing
// output from each function call.
func fetchLogOutputForSpecifiedSeverityLevel(level config.LogSeverity, functions []func()) []string {
// create a logger that writes to buffer at configured level.
var buf bytes.Buffer
var programLevel = new(slog.LevelVar)
logger := slog.New(
defaultLoggerFactory.createJsonOrTextHandler(&buf, programLevel, "TestLogs: "),
)
setLoggingLevel(level, programLevel)

// make the created logger default.
defaultLogger = logger
redirectLogsToGivenBuffer(&buf, level)

var output []string
// run the functions provided.
Expand Down Expand Up @@ -293,3 +294,45 @@ func (t *LoggerTest) TestInitLogFile() {
ExpectEq(backupFileCount, defaultLoggerFactory.logRotateConfig.BackupFileCount)
ExpectEq(true, defaultLoggerFactory.logRotateConfig.Compress)
}

func (t *LoggerTest) TestSetLogFormatToText() {
defaultLoggerFactory = &loggerFactory{
file: nil,
level: config.INFO, // setting log level to INFO by default
logRotateConfig: config.DefaultLogRotateConfig(),
}

testData := []struct {
format string
expectedOutput string
}{
{
"text",
textInfoString,
},
{
"json",
jsonInfoString,
},
{
"",
jsonInfoString,
},
}

for _, test := range testData {
SetLogFormat(test.format)

AssertNe(nil, defaultLoggerFactory)
AssertNe(nil, defaultLogger)
ExpectEq(defaultLoggerFactory.format, test.format)
// Create a logger using defaultLoggerFactory that writes to buffer.
var buf bytes.Buffer
redirectLogsToGivenBuffer(&buf, defaultLoggerFactory.level)
Infof("www.infoExample.com")
output := buf.String()
// Compare expected and actual log.
expectedRegexp := regexp.MustCompile(test.expectedOutput)
ExpectTrue(expectedRegexp.MatchString(output))
}
}
6 changes: 3 additions & 3 deletions internal/logger/slog_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ func addPrefixToMessage(a *slog.Attr, prefix string) {
// time="08/09/2023 09:24:54.437193"
func customiseTimeFormat(a *slog.Attr, format string) {
currTime := a.Value.Any().(time.Time).Round(0)
if format == "json" {
*a = slog.Group(timestampKey, secondsKey, currTime.Unix(), nanosKey, currTime.Nanosecond())
} else {
if format == textFormat {
a.Value = slog.StringValue(currTime.Round(0).Format("02/01/2006 03:04:05.000000"))
} else {
*a = slog.Group(timestampKey, secondsKey, currTime.Unix(), nanosKey, currTime.Nanosecond())
}
}

Expand Down
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,12 @@ func runCLIApp(c *cli.Context) (err error) {
config.OverrideWithLoggingFlags(mountConfig, flags.LogFile, flags.LogFormat,
flags.DebugFuse, flags.DebugGCS, flags.DebugMutex)

// Ideally this call to SetLogFormat (which internally creates a new defaultLogger)
// should be set as an else to the 'if flags.Foreground' check below, but currently
// that means the logs generated by resolveConfigFilePaths below don't honour
// the user-provided log-format.
logger.SetLogFormat(mountConfig.LogConfig.Format)
ashmeenkaur marked this conversation as resolved.
Show resolved Hide resolved

err = resolveConfigFilePaths(mountConfig)
if err != nil {
return fmt.Errorf("Resolving path: %w", err)
Expand Down
Loading