Skip to content

Commit 07019b3

Browse files
committed
Add CustomTextFormatter
Signed-off-by: Šimon Brandner <[email protected]>
1 parent 704d550 commit 07019b3

File tree

2 files changed

+70
-5
lines changed

2 files changed

+70
-5
lines changed

src/logger.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
22+
"github.com/sirupsen/logrus"
23+
)
24+
25+
type CustomTextFormatter struct {
26+
logrus.TextFormatter
27+
logTime bool
28+
}
29+
30+
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
31+
// TODO: Use colors and make it pretty
32+
level := entry.Level
33+
timestamp := entry.Time.Format("2006-01-02 15:04:05")
34+
confID := entry.Data["conf_id"]
35+
userID := entry.Data["user_id"]
36+
37+
logLine := fmt.Sprintf("%s|", level)
38+
39+
if f.logTime {
40+
logLine += fmt.Sprintf("%s|", timestamp)
41+
}
42+
43+
if confID != nil {
44+
logLine += fmt.Sprintf("%v|", confID)
45+
}
46+
47+
if userID != nil {
48+
logLine += fmt.Sprintf("%v|", userID)
49+
}
50+
51+
logLine += fmt.Sprintf(" %v ", entry.Message)
52+
53+
fields := ""
54+
55+
for key, value := range entry.Data {
56+
if key != "conf_id" && key != "user_id" {
57+
fields += fmt.Sprintf("%v=%v ", key, value)
58+
}
59+
}
60+
61+
if fields != "" {
62+
logLine += fmt.Sprintf("| %s", fields)
63+
}
64+
65+
logLine += "\n"
66+
67+
return []byte(logLine), nil
68+
}

src/main.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,9 @@ func initMemoryProfiling(memProfile *string) func() {
8888
}
8989

9090
func initLogging(logTime *bool) {
91-
formatter := new(logrus.TextFormatter)
91+
formatter := new(CustomTextFormatter)
9292

93-
if *logTime {
94-
formatter.FullTimestamp = true
95-
formatter.TimestampFormat = "2006-01-02 15:04:05"
96-
}
93+
formatter.logTime = *logTime
9794

9895
logrus.SetFormatter(formatter)
9996
}

0 commit comments

Comments
 (0)