From c9fa5eb4ab6cb575408882d2fbc85903c4066ba0 Mon Sep 17 00:00:00 2001 From: Simon Ruderich Date: Tue, 25 Nov 2025 08:08:19 +0100 Subject: client: add Logger interface to give programs more control See https://codeberg.org/eduVPN/eduvpn-common/issues/102 --- client/client.go | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) (limited to 'client/client.go') diff --git a/client/client.go b/client/client.go index d986fa6..e3f40aa 100644 --- a/client/client.go +++ b/client/client.go @@ -50,6 +50,17 @@ func CalculateGateway(cidr string) (string, error) { return ret.String(), nil } +// Logger is used by Client to control its logging. Client uses slog for all +// logging which can be configured by implementations of this interface. +type Logger interface { + // Init initializes the logging through slog. The given directory can + // be used to store the log files. + Init(dir string) (*slog.Logger, error) + // Close is called after logging has ended and should release all + // resources from Init. + Close() error +} + // Client is the main struct for the VPN client. type Client struct { // The name of the client @@ -70,8 +81,8 @@ type Client struct { // tokenCacher tokCacher TokenCacher - // logr is the log file rotater - logr *log.FileRotater + // logr is the logger + logr Logger // cfg is the config cfg *config.Config @@ -137,10 +148,10 @@ func (c *Client) goTransition(id fsm.StateID) error { // - name: the name of the client // - directory: the directory where the config files are stored. Absolute or relative // - stateCallback: the callback function for the FSM that takes two states (old and new) and the data as an interface -// - debug: whether or not we want to enable debugging +// - logger: the logger interface to use, if nil the default logger is used which logs to files in directory // // It returns an error if initialization failed, for example when discovery cannot be obtained and when there are no servers. -func New(name string, version string, directory string, stateCallback func(FSMStateID, FSMStateID, any) bool) (c *Client, err error) { +func New(name string, version string, directory string, stateCallback func(FSMStateID, FSMStateID, any) bool, logger Logger) (c *Client, err error) { // We create the client by filling fields one by one c = &Client{} @@ -152,11 +163,16 @@ func New(name string, version string, directory string, stateCallback func(FSMSt return nil, i18nerr.NewInternalf("The client registered with an invalid version: '%v'", version) } - logr, err := log.Init(slog.LevelDebug, directory) + // Initialize provided logger or use default + if logger == nil { + logger = &log.Logger{} + } + c.logr = logger + slogger, err := c.logr.Init(directory) if err != nil { return nil, i18nerr.WrapInternalf(err, "The log file with directory: '%s' failed to initialize", directory) } - c.logr = logr + slog.SetDefault(slogger) // set client name c.Name = name -- cgit v1.2.3