v / vlib / log / file_log_test.v
67 lines · 63 sloc · 1.89 KB · 2332ecff4811b8c97dfda8e825170e9397962519
Raw
1import os
2import log
3import rand
4
5fn test_reopen() {
6 if os.user_os() == 'windows' && os.getenv('SKIP_TEST_REOPEN') == '' {
7 eprintln('skip renaming and reopening a log file on windows')
8 exit(0)
9 }
10 lfolder := os.join_path(os.vtmp_dir(), rand.ulid())
11 lpath1 := os.join_path(lfolder, 'current.log')
12 lpath2 := os.join_path(lfolder, 'current.log.2')
13 os.mkdir_all(lfolder)!
14
15 dump(lfolder)
16 mut l := log.new_thread_safe_log()
17 l.set_level(.debug)
18 l.set_full_logpath(lpath1)
19 l.warn('one warning')
20 l.error('one error')
21 // simulate a log rotation, by moving the log file
22 os.rename(lpath1, lpath2)!
23 l.warn('another warning')
24 // call reopen, note that the message from above, should be in the new file lpath2:
25 l.reopen()!
26 l.warn('third warning')
27 l.flush()
28 l.close()
29 // os.system('ls -la ${lpath1} ${lpath2}')
30 lcontent1 := os.read_file(lpath1)!
31 lcontent2 := os.read_file(lpath2)!
32 assert lcontent1.len > 0
33 assert lcontent2.len > 0
34 // the rotated log should have all messages before the l.reopen() call:
35 assert lcontent2.contains('one warning')
36 assert lcontent2.contains('one error')
37 assert lcontent2.contains('another warning')
38 // the log file that was reopened, should have only the new message:
39 assert lcontent1.contains('third warning')
40 assert !lcontent1.contains('one warning')
41
42 os.rmdir_all(lfolder) or {}
43}
44
45fn test_set_always_flush() {
46 log.set_level(.debug)
47 lfolder := os.join_path(os.vtmp_dir(), rand.ulid())
48 lpath1 := os.join_path(lfolder, 'current.log')
49 os.mkdir_all(lfolder)!
50 defer {
51 os.rmdir_all(lfolder) or {}
52 }
53 dump(lfolder)
54 mut l := log.Log{}
55 l.set_level(.info)
56 l.set_full_logpath(lpath1)
57 l.set_always_flush(true)
58 l.warn('one warning')
59 l.info('one info message')
60 l.error('one error')
61 l.close()
62 lcontent1 := os.read_file(lpath1)!
63 assert lcontent1.len > 0
64 assert lcontent1.contains('one warning')
65 assert lcontent1.contains('one error')
66 assert lcontent1.contains('one info message')
67}
68