github.com/mattdotmatt/gauge@v0.3.2-0.20160421115137-425a4cdccb62/logger/logger.go (about)

     1  // Copyright 2015 ThoughtWorks, Inc.
     2  
     3  // This file is part of Gauge.
     4  
     5  // Gauge is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  
    10  // Gauge is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  
    15  // You should have received a copy of the GNU General Public License
    16  // along with Gauge.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package logger
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  	"path/filepath"
    24  	"strings"
    25  
    26  	"runtime"
    27  
    28  	"github.com/getgauge/common"
    29  	"github.com/getgauge/gauge/config"
    30  	"github.com/op/go-logging"
    31  	"gopkg.in/natefinch/lumberjack.v2"
    32  )
    33  
    34  const (
    35  	logsDirectory    = "logs_directory"
    36  	logs             = "logs"
    37  	gaugeLogFileName = "gauge.log"
    38  	apiLogFileName   = "api.log"
    39  )
    40  
    41  var level logging.Level
    42  var isWindows bool
    43  
    44  // Info logs INFO messages
    45  func Info(msg string, args ...interface{}) {
    46  	GaugeLog.Info(msg, args...)
    47  	fmt.Println(fmt.Sprintf(msg, args...))
    48  }
    49  
    50  // Errorf logs ERROR messages
    51  func Errorf(msg string, args ...interface{}) {
    52  	GaugeLog.Error(msg, args...)
    53  	fmt.Println(fmt.Sprintf(msg, args...))
    54  }
    55  
    56  // Warning logs WARNING messages
    57  func Warning(msg string, args ...interface{}) {
    58  	GaugeLog.Warning(msg, args...)
    59  	fmt.Println(fmt.Sprintf(msg, args...))
    60  }
    61  
    62  // Fatalf logs CRITICAL messages and exits
    63  func Fatalf(msg string, args ...interface{}) {
    64  	fmt.Println(fmt.Sprintf(msg, args...))
    65  	GaugeLog.Fatalf(msg, args...)
    66  }
    67  
    68  // Debug logs DEBUG messages
    69  func Debug(msg string, args ...interface{}) {
    70  	GaugeLog.Debug(msg, args...)
    71  	if level == logging.DEBUG {
    72  		fmt.Println(fmt.Sprintf(msg, args...))
    73  	}
    74  }
    75  
    76  // GaugeLog is for logging messages related to spec execution lifecycle
    77  var GaugeLog = logging.MustGetLogger("gauge")
    78  
    79  // APILog is for logging API related messages
    80  var APILog = logging.MustGetLogger("gauge-api")
    81  
    82  var fileLogFormat = logging.MustStringFormatter("%{time:15:04:05.000} %{message}")
    83  
    84  // Initialize initializes the logger object
    85  func Initialize(logLevel string) {
    86  	level = loggingLevel(logLevel)
    87  	initFileLogger(gaugeLogFileName, GaugeLog)
    88  	initFileLogger(apiLogFileName, APILog)
    89  	if runtime.GOOS == "windows" {
    90  		isWindows = true
    91  	}
    92  }
    93  
    94  func initFileLogger(logFileName string, fileLogger *logging.Logger) {
    95  	customLogsDir := os.Getenv(logsDirectory)
    96  	var backend logging.Backend
    97  	if customLogsDir == "" {
    98  		backend = createFileLogger(filepath.Join(logs, logFileName), 10)
    99  	} else {
   100  		backend = createFileLogger(filepath.Join(customLogsDir, logFileName), 10)
   101  	}
   102  	fileFormatter := logging.NewBackendFormatter(backend, fileLogFormat)
   103  	fileLoggerLeveled := logging.AddModuleLevel(fileFormatter)
   104  	fileLoggerLeveled.SetLevel(logging.DEBUG, "")
   105  
   106  	fileLogger.SetBackend(fileLoggerLeveled)
   107  }
   108  
   109  func createFileLogger(name string, size int) logging.Backend {
   110  	name = getLogFile(name)
   111  	return logging.NewLogBackend(&lumberjack.Logger{
   112  		Filename:   name,
   113  		MaxSize:    size, // megabytes
   114  		MaxBackups: 3,
   115  		MaxAge:     28, //days
   116  	}, "", 0)
   117  }
   118  
   119  func getLogFile(fileName string) string {
   120  	if filepath.IsAbs(fileName) {
   121  		return fileName
   122  	}
   123  	if config.ProjectRoot != "" {
   124  		return filepath.Join(config.ProjectRoot, fileName)
   125  	}
   126  	gaugeHome, err := common.GetGaugeHomeDirectory()
   127  	if err != nil {
   128  		return fileName
   129  	}
   130  	return filepath.Join(gaugeHome, fileName)
   131  }
   132  
   133  func loggingLevel(logLevel string) logging.Level {
   134  	if logLevel != "" {
   135  		switch strings.ToLower(logLevel) {
   136  		case "debug":
   137  			return logging.DEBUG
   138  		case "info":
   139  			return logging.INFO
   140  		case "warning":
   141  			return logging.WARNING
   142  		case "error":
   143  			return logging.ERROR
   144  		}
   145  	}
   146  	return logging.INFO
   147  }
   148  
   149  // HandleWarningMessages logs multiple messages in WARNING mode
   150  func HandleWarningMessages(warnings []string) {
   151  	for _, warning := range warnings {
   152  		GaugeLog.Warning(warning)
   153  	}
   154  }