How to use Reset method of globals Package

Best Ginkgo code snippet using globals.Reset

Run Ginkgo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

sensorBGReset.go

Source: sensorBGReset.go Github

copy
1package sensorManager
2
3import (
4	"fmt"
5	"gateserver/codings"
6	"gateserver/support/globals"
7	"gateserver/support/others"
8	"github.com/fpessolano/mlogger"
9	"strconv"
10	"strings"
11	"time"
12)
13
14func sensorBGReset(forceReset chan string, rst chan interface{}) {
15
16	// return true is successful
17	resetFn := func(channels SensorChannel) bool {
18		cmd := []byte{CmdAPI["rstbg"].Cmd}
19		cmd = append(cmd, codings.Crc8(cmd))
20		var res []byte
21		select {
22		case channels.Commands <- cmd:
23			select {
24			case res = <-channels.Commands:
25			case <-time.After(time.Duration(globals.SensorTimeout) * time.Second):
26			case <-rst:
27				fmt.Println("Closing sensorManager.sensorBGReset")
28				mlogger.Info(globals.SensorManagerLog,
29					mlogger.LoggerData{"sensorManager.sensorBGReset",
30						"service stopped",
31						[]int{0}, true})
32				rst <- nil
33			}
34		case <-time.After(time.Duration(globals.SensorTimeout) * time.Second):
35		}
36		return res != nil
37	}
38
39	mlogger.Info(globals.SensorManagerLog,
40		mlogger.LoggerData{"sensorManager.sensorBGReset",
41			"service started",
42			[]int{0}, true})
43	if globals.ResetSlot != "" {
44		var start, stop time.Time
45		period := strings.Split(globals.ResetSlot, " ")
46		valid := false
47		if v, e := time.Parse(globals.TimeLayout, strings.Trim(period[0], " ")); e == nil {
48			start = v
49			if v, e = time.Parse(globals.TimeLayout, strings.Trim(period[1], " ")); e == nil {
50				stop = v
51				valid = true
52			}
53		}
54		if valid {
55			if globals.DebugActive {
56				fmt.Printf("*** INFO: sensor reset is set from %v tp %v\n", start, stop)
57			}
58			var channels []SensorChannel
59			var macs []string
60			done := false
61			for {
62				select {
63				case <-rst:
64					fmt.Println("Closing sensorManager.sensorBGReset")
65					mlogger.Info(globals.SensorManagerLog,
66						mlogger.LoggerData{"sensorManager.sensorBGReset",
67							"service stopped",
68							[]int{0}, true})
69					rst <- nil
70					return
71				case mac := <-forceReset:
72					// an answer is not needed back to the reset commander
73					ActiveSensors.RLock()
74					chs, ok := ActiveSensors.Mac[mac]
75					ActiveSensors.RUnlock()
76					if ok {
77						// reset
78						if !resetFn(chs) {
79							mlogger.Warning(globals.SensorManagerLog,
80								mlogger.LoggerData{"sensorManager.sensorBGReset: mac " + mac,
81									"reset has failed",
82									[]int{1}, true})
83						}
84					} else {
85						mlogger.Warning(globals.SensorManagerLog,
86							mlogger.LoggerData{"sensorManager.sensorBGReset: mac " + mac,
87								"reset skipped as sensor not active",
88								[]int{0}, true})
89					}
90				case <-time.After(time.Duration(globals.ResetPeriod) * time.Minute):
91					if doIt, e := others.InClosureTime(start, stop); e == nil {
92						//  then cycle among all devices till all are reset
93						if doIt && !done {
94							// we are in the reset interval and we still need to reset
95							if channels == nil {
96								// in this case we need to load the list of devices to be reset
97								ActiveSensors.RLock()
98								for k, v := range ActiveSensors.Mac {
99									macs = append(macs, k)
100									channels = append(channels, v)
101								}
102								ActiveSensors.RUnlock()
103							}
104							var channelsLeft []SensorChannel
105							var macsLeft []string
106							// try to reset all devices
107							for i, el := range channels {
108								if !resetFn(el) {
109									channelsLeft = append(channelsLeft, el)
110									macsLeft = append(macsLeft, macs[i])
111								} else {
112									if globals.DebugActive {
113										fmt.Println("sensorManager.sensorBGReset:", macs[i],
114											"BG reset executed")
115									}
116									mlogger.Info(globals.SensorManagerLog,
117										mlogger.LoggerData{"sensorManager.sensorBGReset: " + macs[i],
118											"BG reset executed",
119											[]int{0}, true})
120								}
121							}
122							if channelsLeft != nil {
123								copy(channels, channelsLeft)
124								copy(macs, macsLeft)
125							} else {
126								channels = nil
127								macs = nil
128							}
129
130							if channelsLeft == nil {
131								done = true
132							}
133						} else {
134							if !doIt {
135								done = false
136								if channels != nil {
137									mlogger.Warning(globals.SensorManagerLog,
138										mlogger.LoggerData{"sensorManager.sensorBGReset",
139											"service failed for " + strconv.Itoa(len(channels)) + " sensors",
140											[]int{}, false})
141									channels = nil
142								}
143							}
144						}
145					} else {
146						// error
147						mlogger.Error(globals.SensorManagerLog,
148							mlogger.LoggerData{"sensorManager.sensorBGReset",
149								"service failed to initialised new loop",
150								[]int{1}, true})
151					}
152				}
153			}
154		}
155	}
156	if globals.DebugActive {
157		fmt.Println("*** WARNING: periodic sensor reset is disabled ***")
158	}
159	// we only listed to reset and forceReset
160	for {
161		select {
162		case <-rst:
163			fmt.Println("Closing sensorManager.sensorBGReset")
164			mlogger.Info(globals.SensorManagerLog,
165				mlogger.LoggerData{"sensorManager.sensorBGReset",
166					"service stopped",
167					[]int{0}, true})
168			rst <- nil
169			return
170		case mac := <-forceReset:
171			// an answer is not needed back to the reset commander
172			ActiveSensors.RLock()
173			chs, ok := ActiveSensors.Mac[mac]
174			ActiveSensors.RUnlock()
175			if ok {
176				// reset
177				if !resetFn(chs) {
178					mlogger.Warning(globals.SensorManagerLog,
179						mlogger.LoggerData{"sensorManager.sensorBGReset: mac " + mac,
180							"reset has failed",
181							[]int{1}, true})
182				}
183			} else {
184				mlogger.Warning(globals.SensorManagerLog,
185					mlogger.LoggerData{"sensorManager.sensorBGReset: mac " + mac,
186						"reset skipped as sensor not active",
187						[]int{0}, true})
188			}
189		}
190	}
191}
192
Full Screen

space.go

Source: space.go Github

copy
1package spaceManager
2
3import (
4	"fmt"
5	"gateserver/avgsManager"
6	"gateserver/dataformats"
7	"gateserver/storage/coredbs"
8	"gateserver/storage/diskCache"
9	"gateserver/support/globals"
10	"gateserver/support/others"
11	"github.com/fpessolano/mlogger"
12	"os"
13	"sync"
14	"time"
15)
16
17var once sync.Once
18
19// updateRegister accumulates the count at space level and passes forth variations only for the rest adjusting for reversed
20func updateRegister(spaceRegister dataformats.SpaceState, data dataformats.EntryState) dataformats.SpaceState {
21	// all space entries and relative gates are reset
22	for key, entry := range spaceRegister.Flows {
23		entry.Variation = 0
24		entry.Ts = data.Ts
25		for i, val := range entry.Flows {
26			val.Variation = 0
27			entry.Flows[i] = val
28		}
29		spaceRegister.Flows[key] = entry
30	}
31
32	// we set the entry/gate variation from the new data (they are received one entry at a time)
33	newEntryData := dataformats.EntryState{
34		Id:       data.Id,
35		Ts:       data.Ts,
36		State:    data.State,
37		Reversed: data.Reversed,
38		Flows:    make(map[string]dataformats.Flow),
39	}
40	if data.Reversed {
41		newEntryData.Variation = -data.Variation
42	} else {
43		newEntryData.Variation = data.Variation
44	}
45	spaceRegister.Flows[data.Id] = newEntryData
46	for name, val := range data.Flows {
47		newGateData := dataformats.Flow{
48			Id:       val.Id,
49			Reversed: val.Reversed,
50		}
51		if data.Reversed {
52			newGateData.Variation = -val.Variation
53		} else {
54			newGateData.Variation = val.Variation
55		}
56		spaceRegister.Flows[data.Id].Flows[name] = newGateData
57	}
58	spaceRegister.Ts = data.Ts
59
60	// the space count is updated
61	for _, entry := range spaceRegister.Flows {
62		spaceRegister.Count += entry.Variation
63	}
64	return spaceRegister
65}
66
67func space(spacename string, spaceRegister, shadowSpaceRegister dataformats.SpaceState, in chan dataformats.EntryState, stop chan interface{},
68	setReset chan bool, entries map[string]dataformats.EntryState, resetSlot []time.Time) {
69
70	// spaceRegister contains the data to be shared with the clients
71	// shadowSpaceRegister is a register copy without adjustments
72	once.Do(func() {
73		if resetSlot != nil {
74			fmt.Printf("*** INFO: Space %v has reset slot set from %v:%v to %v:%v Server Time ***\n",
75				spacename, resetSlot[0].Hour(), resetSlot[0].Minute(), resetSlot[1].Hour(), resetSlot[1].Minute())
76		} else {
77			fmt.Printf("*** INFO: Space %v has not reset slot ***\n", spacename)
78		}
79		// TODO time check can be removed if a cache is used that has timed preserve of state
80		if globals.SaveState {
81			if state, err := diskCache.ReadState(spacename); err == nil {
82				if time.Now().UnixNano() < state.Ts+int64(globals.MaxStateAge)*1000000000 {
83					if state.Id == spacename {
84						spaceRegister = state
85					} else {
86						fmt.Println("*** WARNING: Error reading state for space:", spacename, ". Will assume null state ***")
87					}
88				} else {
89					fmt.Println("*** WARNING: State is too old for space:", spacename, ". Will assume null state ***")
90				}
91			}
92			if state, err := diskCache.ReadShadowState(spacename); err == nil {
93				if time.Now().UnixNano() < state.Ts+int64(globals.MaxStateAge)*1000000000 {
94					if state.Id == spacename {
95						shadowSpaceRegister = state
96					} else {
97						fmt.Println("*** WARNING: Error reading shadow state for space:", spacename, ". Will assume null state ***")
98					}
99				} else {
100					fmt.Println("*** WARNING: Shadow state is too old for space:", spacename, ". Will assume null state ***")
101				}
102			}
103		}
104	})
105
106	defer func() {
107		if e := recover(); e != nil {
108			fmt.Println(e)
109			mlogger.Recovered(globals.SpaceManagerLog,
110				mlogger.LoggerData{"spaceManager.space: " + spacename,
111					"service terminated and recovered unexpectedly",
112					[]int{1}, true})
113		}
114		go space(spacename, spaceRegister, shadowSpaceRegister, in, stop, setReset, entries, resetSlot)
115	}()
116
117	if globals.DebugActive {
118		fmt.Printf("Space %v has been started\n", spacename)
119	}
120	mlogger.Info(globals.SpaceManagerLog,
121		mlogger.LoggerData{"spaceManager.entry: " + spacename,
122			"service started",
123			[]int{0}, true})
124
125	resetDone := false
126	avgsManager.LatestData.RLock()
127	calculator := avgsManager.LatestData.Channel[spacename]
128	avgsManager.LatestData.RUnlock()
129
130	for calculator == nil {
131		fmt.Printf("*** INFO: Space %v waiting for calculator to be ready ***\n", spacename)
132		time.Sleep(time.Duration(globals.SettleTime*3) * time.Second)
133		avgsManager.LatestData.RLock()
134		calculator = avgsManager.LatestData.Channel[spacename]
135		avgsManager.LatestData.RUnlock()
136	}
137
138	for {
139		select {
140		case spaceRegister.State = <-setReset:
141			shadowSpaceRegister.State = spaceRegister.State
142			if globals.DebugActive {
143				fmt.Printf("State of space %v set to %v\n", spacename, spaceRegister.State)
144			}
145			setReset <- spaceRegister.State
146			if spaceRegister.State {
147				mlogger.Info(globals.SpaceManagerLog,
148					mlogger.LoggerData{"spaceManager.space: " + spacename,
149						"state set to true",
150						[]int{0}, true})
151			} else {
152				mlogger.Info(globals.SpaceManagerLog,
153					mlogger.LoggerData{"spaceManager.space: " + spacename,
154						"state set to false",
155						[]int{0}, true})
156			}
157		case <-stop:
158			if globals.SaveState {
159				if err := diskCache.SaveState(spaceRegister); err != nil {
160					fmt.Println("Error saving state for space:", spacename)
161				} else {
162					fmt.Println("Successful saving state for space:", spacename)
163					if err := diskCache.SaveShadowState(shadowSpaceRegister); err != nil {
164						fmt.Println("Error saving shadow state for space:", spacename)
165					} else {
166						fmt.Println("Successful saving shadow state for space:", spacename)
167					}
168				}
169			}
170			fmt.Println("Closing spaceManager.space:", spacename)
171			mlogger.Info(globals.SpaceManagerLog,
172				mlogger.LoggerData{"spacxeManager.entry: " + spacename,
173					"service stopped",
174					[]int{0}, true})
175			stop <- nil
176		case data := <-in:
177			if spaceRegister.State {
178				// space is enabled
179				// we verify if we are in a reset slot
180				resetTime := resetSlot != nil
181				if resetTime {
182					if inTime, err := others.InClosureTime(resetSlot[0], resetSlot[1]); err != nil {
183						mlogger.Warning(globals.SpaceManagerLog,
184							mlogger.LoggerData{"entryManager.entry: " + spacename,
185								"failed to check reset time",
186								[]int{0}, true})
187						continue
188					} else {
189						resetTime = resetTime && inTime
190					}
191				}
192				if resetTime {
193					if !resetDone {
194						select {
195						case calculator <- dataformats.SpaceState{
196							Reset: true,
197						}:
198						case <-time.After(time.Duration(2*globals.SettleTime) * time.Second):
199							if globals.DebugActive {
200								fmt.Println("entryManager.entry:", spacename, "failed to reset flows")
201								os.Exit(0)
202							}
203							mlogger.Warning(globals.SpaceManagerLog,
204								mlogger.LoggerData{Id: "entryManager.entry: " + spacename,
205									Message: "failed to reset flows",
206									Data:    []int{1}, Aggregate: true})
207						}
208
209						resetDone = true
210						spaceRegister.Count = 0
211						spaceRegister.Ts = time.Now().UnixNano()
212						for i, entry := range spaceRegister.Flows {
213							entry.Variation = 0
214							entry.Flows = make(map[string]dataformats.Flow)
215							spaceRegister.Flows[i] = entry
216						}
217						go func(nd dataformats.SpaceState) {
218							_ = coredbs.SaveSpaceData(nd)
219						}(spaceRegister)
220
221					}
222					// the shadow register is always kept updated
223					shadowSpaceRegister = updateRegister(shadowSpaceRegister, data)
224					if globals.Shadowing {
225						go func(nd dataformats.SpaceState) {
226							_ = coredbs.SaveShadowSpaceData(nd)
227						}(shadowSpaceRegister)
228					}
229
230				} else {
231					resetDone = false
232					if data.Variation != 0 {
233						// data is significant
234						// we are in a activity slot
235
236						if _, ok := entries[data.Id]; ok {
237							// entry sending data is in the configuration
238							data.Reversed = entries[data.Id].Reversed
239							timestamp := time.Now().UnixNano()
240
241							// the shadow register is updated with the received data
242							shadowSpaceRegister = updateRegister(shadowSpaceRegister, data)
243							shadowSpaceRegister.Ts = timestamp
244
245							// the data is updated in case it leads to a negative count if the option is enabled
246							if !globals.AcceptNegatives {
247								newData := data.Variation
248								if data.Reversed {
249									newData = -newData
250								}
251								delta := newData + spaceRegister.Count
252								if delta < 0 {
253									// the new data brings the final count below zero
254
255									// the total count is updated according to the reversed flag in order to have final count zero
256									if data.Reversed {
257										data.Variation = spaceRegister.Count
258									} else {
259										data.Variation = -spaceRegister.Count
260									}
261
262									// the new data gate flows are updated according to the delta and the reversed flag
263									entry := dataformats.EntryState{
264										Id:        data.Id,
265										Ts:        data.Ts,
266										Variation: data.Variation,
267										State:     data.State,
268										Reversed:  data.Reversed,
269										Flows:     make(map[string]dataformats.Flow),
270									}
271									for key, value := range data.Flows {
272										// since data was duplicated before being sent, we can use a shallow copy
273										entry.Flows[key] = value
274									}
275
276									// all variations are removed
277									for i := range entry.Flows {
278										flow := entry.Flows[i]
279										flow.Variation = 0
280										entry.Flows[i] = flow
281									}
282
283									delta = data.Variation
284
285									// the new variation is distributed among all gates in the original data
286								finished:
287									for delta != 0 {
288										for i := range entry.Flows {
289											if delta < 0 {
290												flow := entry.Flows[i]
291												flow.Variation -= 1
292												entry.Flows[i] = flow
293												delta += 1
294											} else if delta > 0 {
295												flow := entry.Flows[i]
296												flow.Variation += 1
297												entry.Flows[i] = flow
298												delta -= 1
299											} else {
300												break finished
301											}
302										}
303									}
304
305									data = entry
306								}
307							}
308
309							// register is updated with an inspected received data
310							spaceRegister = updateRegister(spaceRegister, data)
311							// space gets its own timestamp
312							spaceRegister.Ts = timestamp
313
314							if globals.DebugActive {
315								fmt.Printf("Space %v registry data \n\t%+v\n", spacename, spaceRegister)
316							}
317
318							go func(nd dataformats.SpaceState) {
319								_ = coredbs.SaveSpaceData(nd)
320							}(spaceRegister)
321
322							// we give it little time to transmit the data, it too late data is thrown away
323							select {
324							case calculator <- spaceRegister:
325							case <-time.After(time.Duration(globals.SettleTime) * time.Second):
326								if globals.DebugActive {
327									fmt.Println("entryManager.entry:", spacename, "data to calculator discarded due to late answer")
328									os.Exit(0)
329								}
330								mlogger.Warning(globals.SpaceManagerLog,
331									mlogger.LoggerData{Id: "entryManager.entry: " + spacename,
332										Message: "data to calculator discarded due to late answer",
333										Data:    []int{1}, Aggregate: true})
334							}
335
336							if globals.Shadowing {
337								go func(nd dataformats.SpaceState) {
338									_ = coredbs.SaveShadowSpaceData(nd)
339								}(spaceRegister)
340							}
341						} else {
342							mlogger.Warning(globals.SpaceManagerLog,
343								mlogger.LoggerData{Id: "entryManager.entry: " + spacename,
344									Message: "data from entry " + data.Id + " not in configuration",
345									Data:    []int{0}, Aggregate: true})
346						}
347					}
348				}
349			}
350		case <-time.After(time.Duration(globals.ResetPeriod) * time.Minute):
351			if spaceRegister.State {
352				// space is enabled
353				// check if it is a reset interval and act accordingly
354				resetTime := resetSlot != nil
355				if resetTime {
356					if inTime, err := others.InClosureTime(resetSlot[0], resetSlot[1]); err != nil {
357						mlogger.Warning(globals.SpaceManagerLog,
358							mlogger.LoggerData{"entryManager.entry: " + spacename,
359								"failed to check reset time",
360								[]int{0}, true})
361						continue
362					} else {
363						resetTime = resetTime && inTime
364					}
365				}
366				if resetTime {
367					if !resetDone {
368						select {
369						case calculator <- dataformats.SpaceState{
370							Reset: true,
371						}:
372						case <-time.After(time.Duration(2*globals.SettleTime) * time.Second):
373							if globals.DebugActive {
374								fmt.Println("entryManager.entry:", spacename, "failed to reset flows")
375								os.Exit(0)
376							}
377							mlogger.Warning(globals.SpaceManagerLog,
378								mlogger.LoggerData{Id: "entryManager.entry: " + spacename,
379									Message: "failed to reset flows",
380									Data:    []int{1}, Aggregate: true})
381						}
382
383						resetDone = true
384						spaceRegister.Count = 0
385						spaceRegister.Ts = time.Now().UnixNano()
386						for i, entry := range spaceRegister.Flows {
387							entry.Variation = 0
388							entry.Flows = make(map[string]dataformats.Flow)
389							spaceRegister.Flows[i] = entry
390						}
391						go func(nd dataformats.SpaceState) {
392							_ = coredbs.SaveSpaceData(nd)
393						}(spaceRegister)
394
395					}
396				}
397			}
398		}
399	}
400}
401
Full Screen

logger_test.go

Source: logger_test.go Github

copy
1/*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements.  See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership.  The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License.  You may obtain a copy of the License at
9
10     http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17*/
18
19package log
20
21import (
22	"sync"
23	"testing"
24
25	"go.uber.org/zap"
26	"go.uber.org/zap/zapcore"
27	"gotest.tools/assert"
28)
29
30// This test sets the global zap logger. This must be undone to make sure no side
31// effects on other tests are caused by running this test.
32func TestIsNopLogger(t *testing.T) {
33	// reset the global vars and zap logger
34	defer resetGlobals()
35
36	testLogger, err := zap.NewDevelopment()
37	assert.NilError(t, err, "Dev logger init failed with error")
38	assert.Equal(t, false, isNopLogger(testLogger))
39
40	testLogger = zap.NewNop()
41	assert.Equal(t, true, isNopLogger(testLogger))
42
43	testLogger = zap.L()
44	assert.Equal(t, true, isNopLogger(testLogger))
45
46	testLogger, err = zap.NewProduction()
47	assert.NilError(t, err, "Prod logger init failed with error")
48	zap.ReplaceGlobals(testLogger)
49	assert.Equal(t, false, isNopLogger(testLogger))
50	assert.Equal(t, false, isNopLogger(zap.L()))
51}
52
53// Since we test the function IsDebugEnabled() we set the logger global var.
54// It has not triggered the once.Do() so we just need to make sure we clean up the
55// global var.
56func TestIsDebugEnabled(t *testing.T) {
57	// reset the global vars and zap logger
58	defer resetGlobals()
59
60	zapConfig := zap.Config{
61		Level:    zap.NewAtomicLevelAt(zapcore.DebugLevel),
62		Encoding: "console",
63	}
64	var err error
65	logger, err = zapConfig.Build()
66	assert.NilError(t, err, "debug level logger create failed")
67	assert.Equal(t, true, IsDebugEnabled())
68
69	zapConfig = zap.Config{
70		Level:    zap.NewAtomicLevelAt(zapcore.InfoLevel),
71		Encoding: "console",
72	}
73	logger, err = zapConfig.Build()
74	assert.NilError(t, err, "info level logger create failed")
75	assert.Equal(t, false, IsDebugEnabled())
76}
77
78// reset the global vars and the global logger in zap
79func resetGlobals() {
80	logger = nil
81	config = nil
82	once = sync.Once{}
83	zap.ReplaceGlobals(zap.NewNop())
84}
85
86// This test triggers the once.Do() and will have an impact on other tests in this file.
87// resetGlobals() will not undo the impact this test has.
88func TestCreateConfig(t *testing.T) {
89	defer resetGlobals()
90
91	// direct call
92	zapConfig := createConfig()
93	localLogger, err := zapConfig.Build()
94	assert.NilError(t, err, "default config logger create failed")
95	assert.Equal(t, true, localLogger.Core().Enabled(zap.DebugLevel))
96
97	// indirect call to init logger
98	assert.Assert(t, logger == nil, "global logger should not have been set %v", logger)
99	localLogger = Logger()
100	assert.Assert(t, localLogger != nil, "returned logger should have been not nil")
101	// default log level is debug
102	assert.Equal(t, true, IsDebugEnabled())
103	// change log level to info
104	InitAndSetLevel(zap.InfoLevel)
105	assert.Equal(t, false, IsDebugEnabled())
106}
107
108func TestInitializeLogger(t *testing.T) {
109	defer resetGlobals()
110
111	zapConfig := zap.Config{
112		Level:    zap.NewAtomicLevelAt(zapcore.InfoLevel),
113		Encoding: "console",
114	}
115	localLogger, err := zapConfig.Build()
116	assert.NilError(t, err, "failed to create local logger")
117	localLogger2, err2 := zapConfig.Build()
118	assert.NilError(t, err2, "failed to create local logger")
119
120	InitializeLogger(localLogger, &zapConfig)
121	assert.Equal(t, Logger(), localLogger)
122	// second initialization should not do anything
123	InitializeLogger(localLogger2, &zapConfig)
124	assert.Equal(t, Logger(), localLogger)
125}
126
127func TestChangeValidLogLevel(t *testing.T) {
128	defer resetGlobals()
129
130	zapConfig := zap.Config{
131		Level:    zap.NewAtomicLevelAt(zapcore.InfoLevel),
132		Encoding: "console",
133	}
134	localLogger, err := zapConfig.Build()
135	assert.NilError(t, err, "failed to create local logger")
136	InitializeLogger(localLogger, &zapConfig)
137
138	err = SetLogLevel("DEBUG")
139	assert.NilError(t, err, "failed to change log level")
140	assert.Equal(t, zapConfig.Level.Level(), zapcore.DebugLevel)
141
142	// set again to see that we keep DEBUG without issues
143	err = SetLogLevel("DEBUG")
144	assert.NilError(t, err, "failed to change log level")
145	assert.Equal(t, zapConfig.Level.Level(), zapcore.DebugLevel)
146}
147
148func TestChangeInvalidLogLevel(t *testing.T) {
149	defer resetGlobals()
150
151	zapConfig := zap.Config{
152		Level:    zap.NewAtomicLevelAt(zapcore.InfoLevel),
153		Encoding: "console",
154	}
155	localLogger, err := zapConfig.Build()
156	assert.NilError(t, err, "default config logger create failed")
157	InitializeLogger(localLogger, &zapConfig)
158
159	err = SetLogLevel("INVALID")
160	assert.Error(t, err, "failed to change log level, old level active")
161}
162
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in

Trigger Reset code on LambdaTest Cloud Grid

Execute automation tests with Reset on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)