소스 검색

refactor logging to implement #142

tags/v0.9.2-beta
Shivaram Lingamneni 6 년 전
부모
커밋
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
 	Exempted           []string
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
 // LineLenConfig controls line lengths.
134
 // LineLenConfig controls line lengths.
149
 type LineLenConfig struct {
135
 type LineLenConfig struct {
150
 	Tags int
136
 	Tags int
219
 
205
 
220
 	Opers map[string]*OperConfig
206
 	Opers map[string]*OperConfig
221
 
207
 
222
-	Logging []LoggingConfig
208
+	Logging []logger.LoggingConfig
223
 
209
 
224
 	Debug struct {
210
 	Debug struct {
225
 		StackImpact StackImpactConfig
211
 		StackImpact StackImpactConfig
431
 	if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
417
 	if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
432
 		return nil, errors.New("Line lengths must be 512 or greater (check the linelen section under server->limits)")
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
 	for _, logConfig := range config.Logging {
421
 	for _, logConfig := range config.Logging {
436
 		// methods
422
 		// methods
437
 		methods := make(map[string]bool)
423
 		methods := make(map[string]bool)

+ 63
- 28
irc/logger/logger.go 파일 보기

53
 
53
 
54
 // Manager is the main interface used to log debug/info/error messages.
54
 // Manager is the main interface used to log debug/info/error messages.
55
 type Manager struct {
55
 type Manager struct {
56
+	configMutex     sync.RWMutex
56
 	loggers         []singleLogger
57
 	loggers         []singleLogger
57
 	stdoutWriteLock sync.Mutex // use one lock for both stdout and stderr
58
 	stdoutWriteLock sync.Mutex // use one lock for both stdout and stderr
58
 	fileWriteLock   sync.Mutex
59
 	fileWriteLock   sync.Mutex
59
-	DumpingRawInOut bool
60
+	dumpingRawInOut bool
60
 }
61
 }
61
 
62
 
62
 // Config represents the configuration of a single logger.
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
 // NewManager returns a new log manager.
77
 // NewManager returns a new log manager.
77
-func NewManager(config ...Config) (*Manager, error) {
78
+func NewManager(config []LoggingConfig) (*Manager, error) {
78
 	var logger Manager
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
 	for _, logConfig := range config {
102
 	for _, logConfig := range config {
81
 		typeMap := make(map[string]bool)
103
 		typeMap := make(map[string]bool)
82
 		for _, name := range logConfig.Types {
104
 		for _, name := range logConfig.Types {
101
 			fileWriteLock:   &logger.fileWriteLock,
123
 			fileWriteLock:   &logger.fileWriteLock,
102
 		}
124
 		}
103
 		if typeMap["userinput"] || typeMap["useroutput"] || (typeMap["*"] && !(excludedTypeMap["userinput"] && excludedTypeMap["useroutput"])) {
125
 		if typeMap["userinput"] || typeMap["useroutput"] || (typeMap["*"] && !(excludedTypeMap["userinput"] && excludedTypeMap["useroutput"])) {
104
-			logger.DumpingRawInOut = true
126
+			logger.dumpingRawInOut = true
105
 		}
127
 		}
106
 		if sLogger.MethodFile.Enabled {
128
 		if sLogger.MethodFile.Enabled {
107
 			file, err := os.OpenFile(sLogger.MethodFile.Filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
129
 			file, err := os.OpenFile(sLogger.MethodFile.Filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
108
 			if err != nil {
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
 			writer := bufio.NewWriter(file)
133
 			writer := bufio.NewWriter(file)
112
 			sLogger.MethodFile.File = file
134
 			sLogger.MethodFile.File = file
115
 		logger.loggers = append(logger.loggers, sLogger)
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
 // Log logs the given message with the given details.
149
 // Log logs the given message with the given details.
122
 func (logger *Manager) Log(level Level, logType string, messageParts ...string) {
150
 func (logger *Manager) Log(level Level, logType string, messageParts ...string) {
151
+	logger.configMutex.RLock()
152
+	defer logger.configMutex.RUnlock()
153
+
123
 	for _, singleLogger := range logger.loggers {
154
 	for _, singleLogger := range logger.loggers {
124
 		singleLogger.Log(level, logType, messageParts...)
155
 		singleLogger.Log(level, logType, messageParts...)
125
 	}
156
 	}
127
 
158
 
128
 // Debug logs the given message as a debug message.
159
 // Debug logs the given message as a debug message.
129
 func (logger *Manager) Debug(logType string, messageParts ...string) {
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
 // Info logs the given message as an info message.
164
 // Info logs the given message as an info message.
136
 func (logger *Manager) Info(logType string, messageParts ...string) {
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
 // Warning logs the given message as a warning message.
169
 // Warning logs the given message as a warning message.
143
 func (logger *Manager) Warning(logType string, messageParts ...string) {
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
 // Error logs the given message as an error message.
174
 // Error logs the given message as an error message.
150
 func (logger *Manager) Error(logType string, messageParts ...string) {
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
 // Fatal logs the given message as an error message, then exits.
179
 // Fatal logs the given message as an error message, then exits.
179
 	ExcludedTypes   map[string]bool
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
 // Log logs the given message with the given details.
217
 // Log logs the given message with the given details.
183
 func (logger *singleLogger) Log(level Level, logType string, messageParts ...string) {
218
 func (logger *singleLogger) Log(level Level, logType string, messageParts ...string) {
184
 	// no logging enabled
219
 	// no logging enabled

+ 30
- 12
irc/server.go 파일 보기

37
 	couldNotParseIPMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "Unable to parse your IP address")}[0]).Line()
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
 // Limits holds the maximum limits for various things such as topic lengths.
44
 // Limits holds the maximum limits for various things such as topic lengths.
41
 type Limits struct {
45
 type Limits struct {
42
 	AwayLen        int
46
 	AwayLen        int
425
 	c.RplISupport()
429
 	c.RplISupport()
426
 	server.MOTD(c)
430
 	server.MOTD(c)
427
 	c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
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
 	}
1412
 	}
1409
 
1413
 
1410
 	// set RPL_ISUPPORT
1414
 	// set RPL_ISUPPORT
1415
+	var newISupportReplies [][]string
1411
 	oldISupportList := server.isupport
1416
 	oldISupportList := server.isupport
1412
 	server.setISupport()
1417
 	server.setISupport()
1413
 	if oldISupportList != nil {
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
 	server.loadMOTD(config.Server.MOTD)
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
 	if initial {
1431
 	if initial {
1429
 		if err := server.loadDatastore(config.Datastore.Path); err != nil {
1432
 		if err := server.loadDatastore(config.Datastore.Path); err != nil {
1430
 			return err
1433
 			return err
1434
 	// we are now open for business
1437
 	// we are now open for business
1435
 	server.setupListeners(config)
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
 	return nil
1455
 	return nil
1438
 }
1456
 }
1439
 
1457
 

+ 1
- 15
oragono.go 파일 보기

46
 		log.Fatal("Config file did not load successfully:", err.Error())
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
 	if err != nil {
50
 	if err != nil {
65
 		log.Fatal("Logger did not load successfully:", err.Error())
51
 		log.Fatal("Logger did not load successfully:", err.Error())
66
 	}
52
 	}

Loading…
취소
저장