// initLogRotator initializes the logging rotater to write logs to logFile and
// create roll files in the same directory.  It must be called before the
// package-global log rotater variables are used.
1522
func initLogRotator(logFile string) {
	logDir, _ := filepath.Split(logFile)
	err := os.MkdirAll(logDir, 0700)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create log directory: %v\n", err)
		os.Exit(1)
	}
	r, err := rotator.New(logFile, 10*1024, false, 3)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create file rotator: %v\n", err)
		os.Exit(1)
	}

	logRotator = r
}
794623
func (p *Plugin) Init() error {
	if p.Cfg != nil {
		if p.Config == nil {
			p.Config = NewConf()
		}

		_, err := p.Cfg.LoadValue(p.Config)
		if err != nil {
			return err
		}
		p.Log.Debugf("logs config: %+v", p.Config)

		// Handle default log level. Prefer value from environmental variable
		defaultLogLvl := os.Getenv("INITIAL_LOGLVL")
		if defaultLogLvl == "" {
			defaultLogLvl = p.Config.DefaultLevel
		}
		if defaultLogLvl != "" {
			if err := p.LogRegistry.SetLevel("default", defaultLogLvl); err != nil {
				p.Log.Warnf("setting default log level failed: %v", err)
			} else {
				// All loggers created up to this point were created with initial log level set (defined
				// via INITIAL_LOGLVL env. variable with value 'info' by default), so at first, let's set default
				// log level for all of them.
				for loggerName := range p.LogRegistry.ListLoggers() {
					logger, exists := p.LogRegistry.Lookup(loggerName)
					if !exists {
						continue
					}
					logger.SetLevel(logging.ParseLogLevel(defaultLogLvl))
				}
			}
		}

		// Handle config file log levels
		for _, logCfgEntry := range p.Config.Loggers {
			// Put log/level entries from configuration file to the registry.
			if err := p.LogRegistry.SetLevel(logCfgEntry.Name, logCfgEntry.Level); err != nil {
				// Intentionally just log warn & not propagate the error (it is minor thing to interrupt startup)
				p.Log.Warnf("setting log level %s for logger %s failed: %v",
					logCfgEntry.Level, logCfgEntry.Name, err)
			}
		}
		if len(p.Config.Hooks) > 0 {
			p.Log.Info("configuring log hooks")
			for hookName, hookConfig := range p.Config.Hooks {
				if err := p.addHook(hookName, hookConfig); err != nil {
					p.Log.Warnf("configuring log hook %s failed: %v", hookName, err)
				}
			}
		}
	}

	return nil
}
587362
func init() {
	SetPrinter(printer.LogPrinter{})
	_, mainPath, _, _ = runtime.Caller(1)
	mainPath = filepath.Dir(mainPath)
}
1160928
func initLogrus() func() {
	// Initialize logger.LogrusHookBuffer
	logrusHookBuffer = logger.NewLogrusHookBuffer()

	// Initialize logging. All logging is done via logrusHookBuffer;
	// logrus's output writer is always set to ioutil.Discard.
	logrus.AddHook(&logrusHookBuffer)
	logrus.SetOutput(ioutil.Discard)
	logrus.SetLevel(getLogrusLevel(*flagLoglevel))

	switch *flagLogColors {
	case "never", "auto", "always":
	default:
		fmt.Printf("Invalid parameter for -log-colors: '%s'\n", *flagLogColors)
		*flagLogColors = "auto"
	}

	if *flagLogColors == "always" ||
		(*flagLogColors == "auto" && terminal.IsTerminal(int(logger.FallbackLogDevice.Fd()))) {
		// Logrus doesn't know the final log device, so we hint the color option here
		logrus.SetFormatter(logger.NewConsoleFormatter())
	}

	// make sure logs are purged at exit
	return func() {
		logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice)
		logrusHookBuffer.Purge()
	}
}
1214040
func (w *fileLogWriter) startLogger() error {
	file, err := w.createLogFile()
	if err != nil {
		return err
	}
	if w.fileWriter != nil {
		w.fileWriter.Close()
	}
	w.fileWriter = file
	return w.initFd()
}
276311
func (self *RotatingFileHandler) DoRollover() (err error) {
	self.FileHandler.Close()
	defer func() {
		if e := self.FileHandler.Open(); e != nil {
			if e == nil {
				err = e
			}
		}
	}()
	if self.backupCount > 0 {
		filepath := self.GetFilePath()
		for i := self.backupCount - 1; i > 0; i-- {
			sourceFile := fmt.Sprintf("%s.%d", filepath, i)
			destFile := fmt.Sprintf("%s.%d", filepath, i+1)
			if err := self.RotateFile(sourceFile, destFile); err != nil {
				return err
			}
		}
		destFile := fmt.Sprintf("%s.%d", filepath, 1)
		if err := self.RotateFile(filepath, destFile); err != nil {
			return err
		}
	}
	return nil
}
253643
func init() {
	// take an output from a print function
	output := pio.Wrap(logrus.Errorf)
	// register a new printer with name "logrus"
	// which will be able to read text and print as string.
	pio.Register("logrus", output).Marshal(pio.Text)

	// p := pio.Register("logrus", output).Marshal(pio.Text)
	// p.Print("using the logrus printer only")
}
530017
func LogRotate(path string, MaxFileSize int, MaxBackupCount int) {
	//filter .log .trace files
	defer func() {
		if e := recover(); e != nil {
			Logger.Errorf("LogRotate catch an exception")
		}
	}()

	pat := `.(\.log|\.trace|\.out)$`
	fileList, err := FilterFileList(path, pat)
	if err != nil {
		Logger.Errorf("filepath.Walk() path: %s failed.", path)
		return
	}

	for _, file := range fileList {
		logRotateFile(file, MaxFileSize, MaxBackupCount)
	}
}
1192676
func InitLogrus() {
	switch {
	case bool(klog.V(4)):
		serviceability.InitLogrus("DEBUG")
	case bool(klog.V(2)):
		serviceability.InitLogrus("INFO")
	case bool(klog.V(0)):
		serviceability.InitLogrus("WARN")
	}
}
355091
func InitLogger(cfg *LogConfig) error {
	log.SetLevel(stringToLogLevel(cfg.Level))
	log.AddHook(&contextHook{})

	if cfg.Format == "" {
		cfg.Format = DefaultLogFormat
	}
	formatter := stringToLogFormatter(cfg.Format, cfg.DisableTimestamp)
	log.SetFormatter(formatter)

	if len(cfg.File.Filename) != 0 {
		if err := initFileLog(&cfg.File, nil); err != nil {
			return errors.Trace(err)
		}
	}

	if len(cfg.SlowQueryFile) != 0 {
		SlowQueryLogger = log.New()
		tmp := cfg.File
		tmp.Filename = cfg.SlowQueryFile
		if err := initFileLog(&tmp, SlowQueryLogger); err != nil {
			return errors.Trace(err)
		}
		SlowQueryLogger.Formatter = &slowLogFormatter{}
	}

	return nil
}
588182
func (l *LogFile) Rotate() error {
	// rename dest file if it already exists.
	if _, err := os.Stat(l.name); err == nil {
		name := l.name + "." + time.Now().Format(time.RFC3339)
		if err = os.Rename(l.name, name); err != nil {
			return err
		}
	}
	// create new file.
	file, err := os.Create(l.name)
	if err != nil {
		return err
	}
	// switch dest file safely.
	l.mu.Lock()
	file, l.file = l.file, file
	l.mu.Unlock()
	// close old file if open.
	if file != nil {
		if err := file.Close(); err != nil {
			return err
		}
	}
	return nil
}
163916
func InitLogs() {
	log.SetOutput(KlogWriter{})
	log.SetFlags(0)
	// The default glog flush interval is 5 seconds.
	go wait.Until(klog.Flush, *logFlushFreq, wait.NeverStop)
}
1065752
func (w *FileLogWriter) DoRotate() error {
	_, err := os.Lstat(w.Filename)
	if err == nil { // file exists
		// Find the next available number
		num := 1
		fname := ""
		for ; err == nil && num <= 999; num++ {
			fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
			_, err = os.Lstat(fname)
		}
		// return error if the last file checked still existed
		if err == nil {
			return fmt.Errorf("rotate: cannot find free log number to rename %s", w.Filename)
		}

		// block Logger's io.Writer
		w.mw.Lock()
		defer w.mw.Unlock()

		fd := w.mw.fd
		fd.Close()

		// close fd before rename
		// Rename the file to its newfound home
		if err = os.Rename(w.Filename, fname); err != nil {
			return fmt.Errorf("Rotate: %s", err)
		}

		// re-start logger
		if err = w.StartLogger(); err != nil {
			return fmt.Errorf("Rotate StartLogger: %s", err)
		}

		go w.deleteOldLog()
	}

	return nil
}
265007
func InitializeLogger(logJSON bool, lvl string) {
	logger = logrus.New()

	logLevel, err := logrus.ParseLevel(lvl)
	if err != nil {
		logrus.Warnf("unable to parse log level configuration error: %q", err)
		logLevel = logrus.ErrorLevel // reset to ERROR
	}
	logrus.SetLevel(logLevel)
	logger.Level = logLevel

	if logJSON {
		customFormatter := new(logrus.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"

		logrus.SetFormatter(customFormatter)
		customFormatter.DisableTimestamp = false
		logger.Formatter = customFormatter
	} else {
		customFormatter := new(logrus.TextFormatter)
		customFormatter.FullTimestamp = true
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		logrus.SetFormatter(customFormatter)
		logger.Formatter = customFormatter
	}

	logger.Out = os.Stdout
}
305690
func NewFileLogger(f string, o, mode, maxLines, maxRotate, bufsize int) (*FileLogger, error) {
	var file *os.File
	var err error

	switch mode {
	case APPEND:
		// open log file, append if it already exists
		file, err = os.OpenFile(f, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	case TRUNC:
		// just truncate file and start logging
		file, err = os.OpenFile(f, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	case BACKUP:
		// rotate every time a new logger is created
		file, err = openBackup(f, 0, maxRotate)
	case ROTATE:
		// "normal" rotation, when file reaches line limit
		file, err = openBackup(f, maxLines, maxRotate)
	default:
		return nil, fmt.Errorf("Invalid mode parameter: %d", mode)
	}
	if err != nil {
		return nil, fmt.Errorf("Error creating logger: %s", err)
	}

	return newFileLogger(file, o, mode, maxLines, maxRotate, bufsize), nil
}
193630
func RotatingFileHandler(path string, limit uint, formatter Format) (Handler, error) {
	if err := os.MkdirAll(path, 0700); err != nil {
		return nil, err
	}
	files, err := ioutil.ReadDir(path)
	if err != nil {
		return nil, err
	}
	re := regexp.MustCompile(`\.log$`)
	last := len(files) - 1
	for last >= 0 && (!files[last].Mode().IsRegular() || !re.MatchString(files[last].Name())) {
		last--
	}
	var counter *countingWriter
	if last >= 0 && files[last].Size() < int64(limit) {
		// Open the last file, and continue to write into it until it's size reaches the limit.
		if counter, err = prepFile(filepath.Join(path, files[last].Name())); err != nil {
			return nil, err
		}
	}
	if counter == nil {
		counter = new(countingWriter)
	}
	h := StreamHandler(counter, formatter)

	return FuncHandler(func(r *Record) error {
		if counter.count > limit {
			counter.Close()
			counter.w = nil
		}
		if counter.w == nil {
			f, err := os.OpenFile(
				filepath.Join(path, fmt.Sprintf("%s.log", strings.Replace(r.Time.Format("060102150405.00"), ".", "", 1))),
				os.O_CREATE|os.O_APPEND|os.O_WRONLY,
				0600,
			)
			if err != nil {
				return err
			}
			counter.w = f
			counter.count = 0
		}
		return h.Log(r)
	}), nil
}
1222555
func NewRotateFileWriter(p string) *RotateFileWriter {
	// init data
	var tmp RotateFileWriter
	tmp.prefix, _ = filepath.Abs(p)

	// create the first file
	tmp.create()

	return &tmp
}