• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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
16package utils
17
18import (
19	"fmt"
20	"github.com/sirupsen/logrus"
21	"os"
22	"path/filepath"
23	"runtime"
24	"strings"
25)
26
27var LogFile *os.File
28var StdoutFile *os.File
29var osStdout, osStderr = os.Stdout, os.Stderr
30
31func init() {
32	if err := os.MkdirAll("logs", 0750); err != nil {
33		logrus.Errorf("can not make logs dir: %v", err)
34		return
35	}
36	logrus.SetOutput(os.Stdout)
37	logrus.SetReportCaller(true)
38	logrus.SetFormatter(&logrus.TextFormatter{
39		ForceColors:     true,
40		FullTimestamp:   true,
41		TimestampFormat: "2006-01-02 15:04:05",
42		CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
43			funcName := strings.Split(f.Function, ".")
44			fn := funcName[len(funcName)-1]
45			_, filename := filepath.Split(f.File)
46			return fmt.Sprintf("%s()", fn), fmt.Sprintf("%s:%d", filename, f.Line)
47		},
48	})
49}
50
51func ResetLogOutput() {
52	logrus.Info("now log to os stdout...")
53	logrus.SetOutput(osStdout)
54	if LogFile != nil {
55		LogFile.Close()
56	}
57	if StdoutFile != nil {
58		StdoutFile.Close()
59	}
60	LogFile, StdoutFile, os.Stdout, os.Stderr = nil, nil, osStdout, osStderr
61}
62
63func SetLogOutput(pkg string) {
64	file := filepath.Join("logs", pkg+".log")
65	var f *os.File
66	var err error
67	if _, err = os.Stat(file); err == nil {
68		f, err = os.OpenFile(file, os.O_RDWR|os.O_APPEND, 0666)
69	} else {
70		f, err = os.Create(file)
71	}
72	if err != nil {
73		logrus.Errorf("failed to open new log file %s: %v", file, err)
74		return
75	}
76	logrus.Infof("now log to %s", file)
77	logrus.SetOutput(f)
78	if LogFile != nil {
79		LogFile.Close()
80	}
81	LogFile = f
82	stdout := filepath.Join("logs", fmt.Sprintf("%s_stdout.log", pkg))
83	if _, err = os.Stat(stdout); err == nil {
84		f, err = os.OpenFile(stdout, os.O_RDWR|os.O_APPEND, 0666)
85	} else {
86		f, err = os.Create(stdout)
87	}
88	if err != nil {
89		logrus.Errorf("failed to open new stdout log file %s: %v", stdout, err)
90		return
91	}
92	if StdoutFile != nil {
93		StdoutFile.Close()
94	}
95	StdoutFile, os.Stdout, os.Stderr = f, f, f
96	logrus.Infof("re-directing stdout and stderr to %s...", stdout)
97}
98