@@ -3,6 +3,9 @@ module main
3
3
import net.websocket
4
4
import vweb
5
5
import db.sqlite
6
+ import log
7
+ import time
8
+ import os
6
9
7
10
struct Account {
8
11
id int [nonnull; primary]
@@ -18,6 +21,7 @@ struct App {
18
21
pub mut :
19
22
title string
20
23
db sqlite.DB
24
+ logger log.Log
21
25
}
22
26
23
27
const (
@@ -27,7 +31,36 @@ const (
27
31
)
28
32
29
33
pub fn (mut app App) before_request () {
30
- println ('New vweb connection from ${app.ip()} : ${app.req.method} ${app.req.url} ' )
34
+ app.info ('New vweb connection from ${app.ip()} : ${app.req.method} ${app.req.url} ' )
35
+ }
36
+
37
+ fn (mut app App) setup_logger () {
38
+ if ! os.exists ("logs" ) {
39
+ os.mkdir ("logs" ) or {
40
+ app.info ("Cannot create log directory `logs`" )
41
+ }
42
+ }
43
+
44
+ app.logger.set_level (.debug)
45
+
46
+ app.logger.set_full_logpath ("./logs/log_${time.now().ymmdd()} " )
47
+ app.logger.log_to_console_too ()
48
+ }
49
+
50
+ fn (mut app App) info (msg string ) {
51
+ app.logger.info (msg)
52
+
53
+ app.logger.flush ()
54
+ }
55
+
56
+ fn (mut app App) warn (msg string ) {
57
+ app.logger.warn (msg)
58
+
59
+ app.logger.flush ()
60
+ }
61
+
62
+ fn (mut app App) fatal (msg string ) {
63
+ app.logger.fatal (msg)
31
64
}
32
65
33
66
fn main () {
@@ -36,20 +69,28 @@ fn main() {
36
69
title: 'Chat'
37
70
}
38
71
72
+ app.setup_logger ()
73
+
74
+ defer {
75
+ app.logger.close ()
76
+ }
77
+
39
78
app.init_databases ()
40
79
41
80
spawn vweb.run (app, port)
42
81
43
- websocket_server.on_connect (client_connected) or { panic (err) }
82
+ websocket_server.on_connect (app.client_connected) or {
83
+ app.fatal (err.msg ())
84
+ }
44
85
45
86
websocket_server.on_message (message_received)
46
87
47
- websocket_server.listen () or { panic ('Error while listening : ${err} ' ) }
88
+ websocket_server.listen () or { app. fatal ('Error while listening : ${err} ' ) }
48
89
}
49
90
50
- fn client_connected (mut c websocket.ServerClient) ! bool {
91
+ fn (mut app App) client_connected (mut c websocket.ServerClient) ! bool {
51
92
if c.resource_name == '/' {
52
- println ('New websocket connection : ${c.client.conn.peer_addr()!} ' )
93
+ app. info ('New websocket connection : ${c.client.conn.peer_addr()!} ' )
53
94
return true
54
95
}
55
96
return false
0 commit comments