Skip to content

Commit 79b1f91

Browse files
committed
update: business
1 parent ba5afd4 commit 79b1f91

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

rotatelogs.go

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,21 +102,52 @@ func New(p string, options ...Option) (*RotateLogs, error) {
102102
// appropriate file handle that is currently being used.
103103
// If we have reached rotation time, the target file gets
104104
// automatically rotated, and also purged if necessary.
105-
func (rl *RotateLogs) Write(p []byte) (n int, err error) {
105+
func (rl *RotateLogs) Write(bytes []byte) (n int, err error) {
106106
// Guard against concurrent writes
107107
rl.mutex.Lock()
108108
defer rl.mutex.Unlock()
109+
var out io.Writer
110+
if strings.Contains(string(bytes), "business") {
111+
compile := regexp.MustCompile(`{"business": "([^,]+)"}`)
112+
business := compile.FindStringSubmatch(string(bytes))
113+
if len(business) == 2 {
114+
data := string(bytes)
115+
data = compile.ReplaceAllString(data, "")
116+
out, err = rl.getWriterNolock(false, false, business[1])
117+
if err != nil {
118+
return 0, err
119+
}
120+
return out.Write([]byte(data))
121+
} else {
122+
compile = regexp.MustCompile(`"business": "([^,]+)"`)
123+
business = compile.FindStringSubmatch(string(bytes))
124+
if len(business) == 2 {
125+
data := string(bytes)
126+
data = compile.ReplaceAllString(data, "")
127+
out, err = rl.getWriterNolock(false, false, business[1])
128+
if err != nil {
129+
return 0, err
130+
}
131+
return out.Write([]byte(data))
132+
}
133+
}
134+
}
109135

110-
out, err := rl.getWriterNolock(false, false)
136+
out, err = rl.getWriterNolock(false, false, "")
111137
if err != nil {
112138
return 0, errors.Wrap(err, `failed to acquite target io.Writer`)
113139
}
114140

115-
return out.Write(p)
141+
return out.Write(bytes)
116142
}
117143

118144
// must be locked during this operation
119-
func (rl *RotateLogs) getWriterNolock(bailOnRotateFail, useGenerationalNames bool) (io.Writer, error) {
145+
func (rl *RotateLogs) getWriterNolock(bailOnRotateFail, useGenerationalNames bool, business string) (io.Writer, error) {
146+
if business != "" {
147+
slice := strings.Split(rl.pattern.Pattern(), "/")
148+
slice = append(slice[:len(slice)-1], business, slice[len(slice)-1])
149+
rl.pattern, _ = strftime.New(strings.Join(slice, "/"))
150+
}
120151
generation := rl.generation
121152
previousFn := rl.curFn
122153

@@ -248,7 +279,7 @@ func (g *cleanupGuard) Run() {
248279
func (rl *RotateLogs) Rotate() error {
249280
rl.mutex.Lock()
250281
defer rl.mutex.Unlock()
251-
_, err := rl.getWriterNolock(true, true)
282+
_, err := rl.getWriterNolock(true, true, "")
252283

253284
return err
254285
}

0 commit comments

Comments
 (0)