Просмотр исходного кода

refactor logging to implement #142

tags/v0.9.2-beta
Shivaram Lingamneni 6 лет назад
Родитель
Сommit
aff1752d67
4 измененных файлов: 96 добавлений и 71 удалений
  1. 2
    16
      irc/config.go
  2. 63
    28
      irc/logger/logger.go
  3. 30
    12
      irc/server.go
  4. 1
    15
      oragono.go

+ 2
- 16
irc/config.go Просмотреть файл

@@ -131,20 +131,6 @@ type ConnectionThrottleConfig struct {
131 131
 	Exempted           []string
132 132
 }
133 133
 
134
-// LoggingConfig controls a single logging method.
135
-type LoggingConfig struct {
136
-	Method        string
137
-	MethodStdout  bool
138
-	MethodStderr  bool
139
-	MethodFile    bool
140
-	Filename      string
141
-	TypeString    string       `yaml:"type"`
142
-	Types         []string     `yaml:"real-types"`
143
-	ExcludedTypes []string     `yaml:"real-excluded-types"`
144
-	LevelString   string       `yaml:"level"`
145
-	Level         logger.Level `yaml:"level-real"`
146
-}
147
-
148 134
 // LineLenConfig controls line lengths.
149 135
 type LineLenConfig struct {
150 136
 	Tags int
@@ -219,7 +205,7 @@ type Config struct {
219 205
 
220 206
 	Opers map[string]*OperConfig
221 207
 
222
-	Logging []LoggingConfig
208
+	Logging []logger.LoggingConfig
223 209
 
224 210
 	Debug struct {
225 211
 		StackImpact StackImpactConfig
@@ -431,7 +417,7 @@ func LoadConfig(filename string) (config *Config, err error) {
431 417
 	if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
432 418
 		return nil, errors.New("Line lengths must be 512 or greater (check the linelen section under server->limits)")
433 419
 	}
434
-	var newLogConfigs []LoggingConfig
420
+	var newLogConfigs []logger.LoggingConfig
435 421
 	for _, logConfig := range config.Logging {
436 422
 		// methods
437 423
 		methods := make(map[string]bool)

+ 63
- 28
irc/logger/logger.go Просмотреть файл

@@ -53,30 +53,52 @@ var (
53 53
 
54 54
 // Manager is the main interface used to log debug/info/error messages.
55 55
 type Manager struct {
56
+	configMutex     sync.RWMutex
56 57
 	loggers         []singleLogger
57 58
 	stdoutWriteLock sync.Mutex // use one lock for both stdout and stderr
58 59
 	fileWriteLock   sync.Mutex
59
-	DumpingRawInOut bool
60
+	dumpingRawInOut bool
60 61
 }
61 62
 
62 63
 // Config represents the configuration of a single logger.
63
-type Config struct {
64
-	// logging methods
65
-	MethodStdout bool
66
-	MethodStderr bool
67
-	MethodFile   bool
68
-	Filename     string
69
-	// logging level
70
-	Level Level
71
-	// logging types
72
-	Types         []string
73
-	ExcludedTypes []string
64
+type LoggingConfig struct {
65
+	Method        string
66
+	MethodStdout  bool
67
+	MethodStderr  bool
68
+	MethodFile    bool
69
+	Filename      string
70
+	TypeString    string   `yaml:"type"`
71
+	Types         []string `yaml:"real-types"`
72
+	ExcludedTypes []string `yaml:"real-excluded-types"`
73
+	LevelString   string   `yaml:"level"`
74
+	Level         Level    `yaml:"level-real"`
74 75
 }
75 76
 
76 77
 // NewManager returns a new log manager.
77
-func NewManager(config ...Config) (*Manager, error) {
78
+func NewManager(config []LoggingConfig) (*Manager, error) {
78 79
 	var logger Manager
79 80
 
81
+	if err := logger.ApplyConfig(config); err != nil {
82
+		return nil, err
83
+	}
84
+
85
+	return &logger, nil
86
+}
87
+
88
+func (logger *Manager) ApplyConfig(config []LoggingConfig) error {
89
+	logger.configMutex.Lock()
90
+	defer logger.configMutex.Unlock()
91
+
92
+	for _, logger := range logger.loggers {
93
+		logger.Close()
94
+	}
95
+
96
+	logger.loggers = nil
97
+	logger.dumpingRawInOut = false
98
+
99
+	// for safety, this deep-copies all mutable data in `config`
100
+	// XXX let's keep it that way
101
+	var lastErr error
80 102
 	for _, logConfig := range config {
81 103
 		typeMap := make(map[string]bool)
82 104
 		for _, name := range logConfig.Types {
@@ -101,12 +123,12 @@ func NewManager(config ...Config) (*Manager, error) {
101 123
 			fileWriteLock:   &logger.fileWriteLock,
102 124
 		}
103 125
 		if typeMap["userinput"] || typeMap["useroutput"] || (typeMap["*"] && !(excludedTypeMap["userinput"] && excludedTypeMap["useroutput"])) {
104
-			logger.DumpingRawInOut = true
126
+			logger.dumpingRawInOut = true
105 127
 		}
106 128
 		if sLogger.MethodFile.Enabled {
107 129
 			file, err := os.OpenFile(sLogger.MethodFile.Filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
108 130
 			if err != nil {
109
-				return nil, fmt.Errorf("Could not open log file %s [%s]", sLogger.MethodFile.Filename, err.Error())
131
+				lastErr = fmt.Errorf("Could not open log file %s [%s]", sLogger.MethodFile.Filename, err.Error())
110 132
 			}
111 133
 			writer := bufio.NewWriter(file)
112 134
 			sLogger.MethodFile.File = file
@@ -115,11 +137,20 @@ func NewManager(config ...Config) (*Manager, error) {
115 137
 		logger.loggers = append(logger.loggers, sLogger)
116 138
 	}
117 139
 
118
-	return &logger, nil
140
+	return lastErr
141
+}
142
+
143
+func (logger *Manager) DumpingRawInOut() bool {
144
+	logger.configMutex.RLock()
145
+	defer logger.configMutex.RUnlock()
146
+	return logger.dumpingRawInOut
119 147
 }
120 148
 
121 149
 // Log logs the given message with the given details.
122 150
 func (logger *Manager) Log(level Level, logType string, messageParts ...string) {
151
+	logger.configMutex.RLock()
152
+	defer logger.configMutex.RUnlock()
153
+
123 154
 	for _, singleLogger := range logger.loggers {
124 155
 		singleLogger.Log(level, logType, messageParts...)
125 156
 	}
@@ -127,30 +158,22 @@ func (logger *Manager) Log(level Level, logType string, messageParts ...string)
127 158
 
128 159
 // Debug logs the given message as a debug message.
129 160
 func (logger *Manager) Debug(logType string, messageParts ...string) {
130
-	for _, singleLogger := range logger.loggers {
131
-		singleLogger.Log(LogDebug, logType, messageParts...)
132
-	}
161
+	logger.Log(LogDebug, logType, messageParts...)
133 162
 }
134 163
 
135 164
 // Info logs the given message as an info message.
136 165
 func (logger *Manager) Info(logType string, messageParts ...string) {
137
-	for _, singleLogger := range logger.loggers {
138
-		singleLogger.Log(LogInfo, logType, messageParts...)
139
-	}
166
+	logger.Log(LogInfo, logType, messageParts...)
140 167
 }
141 168
 
142 169
 // Warning logs the given message as a warning message.
143 170
 func (logger *Manager) Warning(logType string, messageParts ...string) {
144
-	for _, singleLogger := range logger.loggers {
145
-		singleLogger.Log(LogWarning, logType, messageParts...)
146
-	}
171
+	logger.Log(LogWarning, logType, messageParts...)
147 172
 }
148 173
 
149 174
 // Error logs the given message as an error message.
150 175
 func (logger *Manager) Error(logType string, messageParts ...string) {
151
-	for _, singleLogger := range logger.loggers {
152
-		singleLogger.Log(LogError, logType, messageParts...)
153
-	}
176
+	logger.Log(LogError, logType, messageParts...)
154 177
 }
155 178
 
156 179
 // Fatal logs the given message as an error message, then exits.
@@ -179,6 +202,18 @@ type singleLogger struct {
179 202
 	ExcludedTypes   map[string]bool
180 203
 }
181 204
 
205
+func (logger *singleLogger) Close() error {
206
+	if logger.MethodFile.Enabled {
207
+		flushErr := logger.MethodFile.Writer.Flush()
208
+		closeErr := logger.MethodFile.File.Close()
209
+		if flushErr != nil {
210
+			return flushErr
211
+		}
212
+		return closeErr
213
+	}
214
+	return nil
215
+}
216
+
182 217
 // Log logs the given message with the given details.
183 218
 func (logger *singleLogger) Log(level Level, logType string, messageParts ...string) {
184 219
 	// no logging enabled

+ 30
- 12
irc/server.go Просмотреть файл

@@ -37,6 +37,10 @@ var (
37 37
 	couldNotParseIPMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "Unable to parse your IP address")}[0]).Line()
38 38
 )
39 39
 
40
+const (
41
+	rawOutputNotice = "This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect."
42
+)
43
+
40 44
 // Limits holds the maximum limits for various things such as topic lengths.
41 45
 type Limits struct {
42 46
 	AwayLen        int
@@ -425,8 +429,8 @@ func (server *Server) tryRegister(c *Client) {
425 429
 	c.RplISupport()
426 430
 	server.MOTD(c)
427 431
 	c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
428
-	if server.logger.DumpingRawInOut {
429
-		c.Notice("This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect.")
432
+	if server.logger.DumpingRawInOut() {
433
+		c.Notice(rawOutputNotice)
430 434
 	}
431 435
 }
432 436
 
@@ -1408,23 +1412,22 @@ func (server *Server) applyConfig(config *Config, initial bool) error {
1408 1412
 	}
1409 1413
 
1410 1414
 	// set RPL_ISUPPORT
1415
+	var newISupportReplies [][]string
1411 1416
 	oldISupportList := server.isupport
1412 1417
 	server.setISupport()
1413 1418
 	if oldISupportList != nil {
1414
-		newISupportReplies := oldISupportList.GetDifference(server.isupport)
1415
-		// push new info to all of our clients
1416
-		server.clients.ByNickMutex.RLock()
1417
-		for _, sClient := range server.clients.ByNick {
1418
-			for _, tokenline := range newISupportReplies {
1419
-				// ugly trickery ahead
1420
-				sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
1421
-			}
1422
-		}
1423
-		server.clients.ByNickMutex.RUnlock()
1419
+		newISupportReplies = oldISupportList.GetDifference(server.isupport)
1424 1420
 	}
1425 1421
 
1426 1422
 	server.loadMOTD(config.Server.MOTD)
1427 1423
 
1424
+	// reload logging config
1425
+	err = server.logger.ApplyConfig(config.Logging)
1426
+	if err != nil {
1427
+		return err
1428
+	}
1429
+	dumpingRawInOut := server.logger.DumpingRawInOut()
1430
+
1428 1431
 	if initial {
1429 1432
 		if err := server.loadDatastore(config.Datastore.Path); err != nil {
1430 1433
 			return err
@@ -1434,6 +1437,21 @@ func (server *Server) applyConfig(config *Config, initial bool) error {
1434 1437
 	// we are now open for business
1435 1438
 	server.setupListeners(config)
1436 1439
 
1440
+	if !initial {
1441
+		// push new info to all of our clients
1442
+		server.clients.ByNickMutex.RLock()
1443
+		for _, sClient := range server.clients.ByNick {
1444
+			for _, tokenline := range newISupportReplies {
1445
+				sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
1446
+			}
1447
+
1448
+			if dumpingRawInOut {
1449
+				sClient.Notice(rawOutputNotice)
1450
+			}
1451
+		}
1452
+		server.clients.ByNickMutex.RUnlock()
1453
+	}
1454
+
1437 1455
 	return nil
1438 1456
 }
1439 1457
 

+ 1
- 15
oragono.go Просмотреть файл

@@ -46,21 +46,7 @@ Options:
46 46
 		log.Fatal("Config file did not load successfully:", err.Error())
47 47
 	}
48 48
 
49
-	// assemble separate log configs
50
-	var logConfigs []logger.Config
51
-	for _, lConfig := range config.Logging {
52
-		logConfigs = append(logConfigs, logger.Config{
53
-			MethodStdout:  lConfig.MethodStdout,
54
-			MethodStderr:  lConfig.MethodStderr,
55
-			MethodFile:    lConfig.MethodFile,
56
-			Filename:      lConfig.Filename,
57
-			Level:         lConfig.Level,
58
-			Types:         lConfig.Types,
59
-			ExcludedTypes: lConfig.ExcludedTypes,
60
-		})
61
-	}
62
-
63
-	logger, err := logger.NewManager(logConfigs...)
49
+	logger, err := logger.NewManager(config.Logging)
64 50
 	if err != nil {
65 51
 		log.Fatal("Logger did not load successfully:", err.Error())
66 52
 	}

Загрузка…
Отмена
Сохранить