]> Cypherpunks.ru repositories - goircd.git/blob - log.go
Many fixes and additions
[goircd.git] / log.go
1 /*
2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2020 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package main
19
20 import (
21         "fmt"
22         "log"
23         "os"
24         "path"
25         "time"
26 )
27
28 const (
29         FormatMsg  = "[%s] <%s> %s\n"
30         FormatMeta = "[%s] * %s %s\n"
31 )
32
33 var logSink chan LogEvent = make(chan LogEvent)
34
35 type LogEvent struct {
36         where string
37         who   string
38         what  string
39         meta  bool
40 }
41
42 func Logger(logdir string, events <-chan LogEvent) {
43         mode := os.O_CREATE | os.O_WRONLY | os.O_APPEND
44         perm := os.FileMode(permLogFile)
45         var format string
46         var logfile string
47         var fd *os.File
48         var err error
49         for event := range events {
50                 logfile = path.Join(logdir, event.where+".log")
51                 fd, err = os.OpenFile(logfile, mode, perm)
52                 if err != nil {
53                         log.Println("can not open logfile", logfile, err)
54                         continue
55                 }
56                 if event.meta {
57                         format = FormatMeta
58                 } else {
59                         format = FormatMsg
60                 }
61                 _, err = fd.WriteString(fmt.Sprintf(
62                         format,
63                         time.Now().Format(time.RFC3339),
64                         event.who,
65                         event.what,
66                 ))
67                 fd.Close()
68                 if err != nil {
69                         log.Println("error writing to logfile", logfile, err)
70                 }
71         }
72 }