Is there a way to get `*state.GlobalState.Logger` in extension?

I write a k6 extension, and want to display logs controller by k6.

i.e.

# show info logs
./k6 run 

# show debug logs 
./k6 run -v

How can I do this in my extension or modules.Register?

Hi @Harris_1!

If I understand correctly, you want to write debug and info logs in your extension.
If we take this extension as an example: JavaScript Extensions
You can write into the IsGreater(a, b int) function on the line 54 the following:

	c.vu.State().Logger.Debug("This is a debug log")
	c.vu.State().Logger.Info("This is an info log")

Does this answer help you?

3 Likes

Thanks for your reply, seems ok for me.

1 Like

Certainly! To access *state.GlobalState.Logger in an extension, ensure it’s properly exposed or accessible. If it’s part of a global state, use the appropriate context or API provided by the extension framework. Double-check the extension documentation for explicit guidance on accessing the logger within your extension code. If the logger isn’t directly accessible, consider creating a helper function or exposing it via an extension API to make it available where needed. Always adhere to best practices and security considerations outlined by the extension framework.

1 Like

package state

import (
go.uber.org/zap
)

// GlobalState holds the global logger instance.
type GlobalState struct {
Logger *zap.Logger
}

var Global *GlobalState

func init() {
// Initialize the global state and logger
logger, _ := zap.NewProduction()
Global = &GlobalState{
Logger: logger,

}

}