github.com/astaxie/beego@v1.12.3/logs/multifile_test.go (about)

     1  // Copyright 2014 beego Author. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package logs
    16  
    17  import (
    18  	"bufio"
    19  	"os"
    20  	"strconv"
    21  	"strings"
    22  	"testing"
    23  )
    24  
    25  func TestFiles_1(t *testing.T) {
    26  	log := NewLogger(10000)
    27  	log.SetLogger("multifile", `{"filename":"test.log","separate":["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"]}`)
    28  	log.Debug("debug")
    29  	log.Informational("info")
    30  	log.Notice("notice")
    31  	log.Warning("warning")
    32  	log.Error("error")
    33  	log.Alert("alert")
    34  	log.Critical("critical")
    35  	log.Emergency("emergency")
    36  	fns := []string{""}
    37  	fns = append(fns, levelNames[0:]...)
    38  	name := "test"
    39  	suffix := ".log"
    40  	for _, fn := range fns {
    41  
    42  		file := name + suffix
    43  		if fn != "" {
    44  			file = name + "." + fn + suffix
    45  		}
    46  		f, err := os.Open(file)
    47  		if err != nil {
    48  			t.Fatal(err)
    49  		}
    50  		b := bufio.NewReader(f)
    51  		lineNum := 0
    52  		lastLine := ""
    53  		for {
    54  			line, _, err := b.ReadLine()
    55  			if err != nil {
    56  				break
    57  			}
    58  			if len(line) > 0 {
    59  				lastLine = string(line)
    60  				lineNum++
    61  			}
    62  		}
    63  		var expected = 1
    64  		if fn == "" {
    65  			expected = LevelDebug + 1
    66  		}
    67  		if lineNum != expected {
    68  			t.Fatal(file, "has", lineNum, "lines not "+strconv.Itoa(expected)+" lines")
    69  		}
    70  		if lineNum == 1 {
    71  			if !strings.Contains(lastLine, fn) {
    72  				t.Fatal(file + " " + lastLine + " not contains the log msg " + fn)
    73  			}
    74  		}
    75  		os.Remove(file)
    76  	}
    77  
    78  }