//NewLogger creates a //logger for logrus func NewLogger(cfg configFile) *log.Logger { //This creates new logger Log = log.New() Log.Formatter = new(log.JSONFormatter) Log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ log.InfoLevel: cfg.Log.Path, log.ErrorLevel: cfg.Log.Path, log.DebugLevel: cfg.Log.Path, })) Log.Hooks.Add(&metricsHook{ metrics, }) client, err := elastic.NewClient( elastic.SetURL(cfg.Elastic.URL), elastic.SetBasicAuth(cfg.Elastic.Username, cfg.Elastic.Password)) if err != nil { log.Error(err) } else { hook, err := elogrus.NewElasticHook(client, cfg.Server.Host, log.DebugLevel, "goplag") if err != nil { log.Error(err) } else { Log.Hooks.Add(hook) } } return Log }
func setupFileLogging(logFile string) { log.Printf("Logging to file=[%s]", logFile) logrusFileHook := lfshook.NewHook(lfshook.PathMap{ log.InfoLevel: logFile, log.WarnLevel: logFile, log.ErrorLevel: logFile, log.FatalLevel: logFile, log.PanicLevel: logFile, }) log.AddHook(logrusFileHook) }
func AddLogFile(filename string) { log.AddHook(lfshook.NewHook(lfshook.PathMap{ log.DebugLevel: filename, log.InfoLevel: filename, log.WarnLevel: filename, log.ErrorLevel: filename, log.FatalLevel: filename, log.PanicLevel: filename, })) }
func SetLogFile(logFile string) { hook := lfshook.NewHook(lfshook.PathMap{ logrus.DebugLevel: logFile, logrus.InfoLevel: logFile, logrus.WarnLevel: logFile, logrus.ErrorLevel: logFile, logrus.FatalLevel: logFile, }) logger.Hooks.Add(hook) }
func TestSMPPTranceiver(t *testing.T) { // формируем параметры авторизации bindParams := smpp.Params{ smpp.SYSTEM_TYPE: "SMPP", smpp.SYSTEM_ID: "Zultys", smpp.PASSWORD: "******", } logrus.SetLevel(logrus.DebugLevel) logrus.AddHook(lfshook.NewHook(lfshook.PathMap{ logrus.InfoLevel: "info.log", logrus.ErrorLevel: "error.log", logrus.DebugLevel: "debug.log", logrus.WarnLevel: "warning.log", })) logrus.SetFormatter(new(prefixed.TextFormatter)) Logger := logrus.StandardLogger().WithField("smpp", addr) trx, err := NewTransceiver(addr, 0, bindParams, Logger) if err != nil { Logger.WithError(err).Error("Connect error") t.Fatal(err) } defer trx.Close() receive := make(chan interface{}, 10) // канал для получения SMS status := make(chan Status, 10) // канал для получения статусов доставки response := make(chan SendResponse, 10) // канал для получения подтверждений отправки go func() { for { select { case msg := <-receive: Logger.Debugln("Receive:", msg) case msg := <-status: Logger.Debugln("Status:", msg) case msg := <-response: Logger.Debugln("Response:", msg) } } }() go trx.reading(receive) // запускаем получение данных с сервера for _, text := range texts { time.Sleep(time.Second * 10) sms := &SendMessage{ From: from, To: to2, Text: text, } err := trx.Send(sms) if err != nil { Logger.WithError(err).Error("Send error") t.Error(err) } Logger.WithField("seqs", sms.Seq).Info("Sended") } time.Sleep(time.Minute * 5) }
//InitLog system func InitLog() { log.SetOutput(os.Stderr) log.SetLevel(log.WarnLevel) Log = log.New() LogWriter = Log.Writer() Log.Formatter = new(log.JSONFormatter) Log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ log.InfoLevel: "log/info.log", log.ErrorLevel: "log/error.log", })) }
func initLogging() { // level level, err := logrus.ParseLevel(viper.GetString("log-level")) if err != nil { logrus.WithError(err).Warn(`invalid log level. Defaulting to "info"`) level = logrus.InfoLevel } logrus.SetLevel(level) // format switch viper.GetString("log-format") { case "text": logrus.SetFormatter(new(logrus.TextFormatter)) case "json": logrus.SetFormatter(new(logrus.JSONFormatter)) default: logrus.SetFormatter(new(logrus.TextFormatter)) logrus.WithField("format", viper.GetString("log-format")).Warn(`invalid log format. Defaulting to "text"`) } // output dest, err := url.Parse(viper.GetString("log-destination")) if err != nil { logrus.WithError(err).WithField("destination", viper.GetString("log-destination")).Error(`invalid log destination. Defaulting to "stdout:"`) dest.Scheme = "stdout" } switch dest.Scheme { case "stdout": // default, we don't need to do anything case "file": logrus.AddHook(lfshook.NewHook(lfshook.PathMap{ logrus.DebugLevel: dest.Opaque, logrus.InfoLevel: dest.Opaque, logrus.WarnLevel: dest.Opaque, logrus.ErrorLevel: dest.Opaque, logrus.FatalLevel: dest.Opaque, })) case "journald": journalhook.Enable() case "syslog": hook, err := logrus_syslog.NewSyslogHook(dest.Fragment, dest.Host, syslog.LOG_DEBUG, dest.User.String()) if err != nil { logrus.WithError(err).Error("could not configure syslog hook") } else { logrus.AddHook(hook) } default: logrus.WithField("destination", viper.GetString("log-destination")).Warn(`invalid log destination. Defaulting to "stdout:"`) } }
//InitLog system func InitLogger() { if Log == nil { log.SetOutput(os.Stderr) log.SetLevel(log.WarnLevel) Log = log.New() Log.Formatter = new(log.JSONFormatter) fmt.Printf("LOADED LOG %s", os.Getenv("MODE")) if os.Getenv("MODE") == "production" { Log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ log.InfoLevel: "log/info.log", log.ErrorLevel: "log/error.log", })) } } }
// NewCustomLogger creates logrus func NewCustomLogger(c config.ServerInfo) *logrus.Entry { log := logrus.New() log.Formatter = &formatter.TextFormatter{MsgAnsiColor: c.LogMsgAnsiColor} log.Out = os.Stderr log.Level = logrus.InfoLevel if config.Conf.Debug { log.Level = logrus.DebugLevel } // File output logDir := "/var/log/vuls" if runtime.GOOS == "windows" { logDir = filepath.Join(os.Getenv("APPDATA"), "vuls") } if _, err := os.Stat(logDir); os.IsNotExist(err) { if err := os.Mkdir(logDir, 0666); err != nil { logrus.Errorf("Failed to create log directory: %s", err) } } whereami := "localhost" if 0 < len(c.ServerName) { if 0 < len(c.Container.ContainerID) { whereami = fmt.Sprintf( "%s_%s", c.ServerName, c.Container.Name) } else { whereami = fmt.Sprintf("%s", c.ServerName) } } if _, err := os.Stat(logDir); err == nil { path := filepath.Join(logDir, whereami) log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ logrus.DebugLevel: path, logrus.InfoLevel: path, logrus.WarnLevel: path, logrus.ErrorLevel: path, logrus.FatalLevel: path, logrus.PanicLevel: path, })) } fields := logrus.Fields{"prefix": whereami} return log.WithFields(fields) }
// NewLocalParser return local site func NewLocalParser(owner, contextDir string) (*Parser, error) { s, err := local.New(contextDir) if err != nil { return nil, err } config, sites, defaultSite := loadConfigAndSites(s) s.SourcePath = filepath.Join(s.RootPath, config.Source) s.DestinationPath = filepath.Join(s.RootPath, config.Destination) warnPath := s.GetSourceKey(PrefixLogs, "warn.log") errorPath := s.GetSourceKey(PrefixLogs, "error.log") if !s.IsExist(warnPath) { s.Write(warnPath, []byte{}) } if !s.IsExist(errorPath) { s.Write(errorPath, []byte{}) } cacheFiles := make(map[string][]byte) logger := log.New() logger.Formatter = new(log.TextFormatter) logger.Level = log.WarnLevel logger.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ log.WarnLevel: warnPath, log.ErrorLevel: errorPath, })) parser := &Parser{ Owner: owner, Name: s.Name, Path: s.RootPath, Config: config, Sites: sites, Default: defaultSite, Current: defaultSite, cacheFiles: cacheFiles, logger: logger, } parser.Storage = s return parser, nil }
// NewCustomLogger creates logrus func NewCustomLogger(c config.ServerInfo) *logrus.Entry { log := logrus.New() log.Formatter = &formatter.TextFormatter{MsgAnsiColor: c.LogMsgAnsiColor} log.Out = os.Stderr log.Level = logrus.InfoLevel if config.Conf.Debug { log.Level = logrus.DebugLevel } // File output logDir := GetDefaultLogDir() if 0 < len(config.Conf.LogDir) { logDir = config.Conf.LogDir } if _, err := os.Stat(logDir); os.IsNotExist(err) { if err := os.Mkdir(logDir, 0700); err != nil { logrus.Errorf("Failed to create log directory: %s", err) } } whereami := "localhost" if 0 < len(c.ServerName) { whereami = c.GetServerName() } if _, err := os.Stat(logDir); err == nil { path := filepath.Join(logDir, whereami) log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ logrus.DebugLevel: path, logrus.InfoLevel: path, logrus.WarnLevel: path, logrus.ErrorLevel: path, logrus.FatalLevel: path, logrus.PanicLevel: path, })) } fields := logrus.Fields{"prefix": whereami} return log.WithFields(fields) }
func GetLogger(logLevelFilePathMap map[log.Level]string) *log.Logger { if _logger != nil { return _logger } //create if not exist for _, path := range logLevelFilePathMap { if _, err := os.Stat(path); os.IsNotExist(err) { file, err := os.Create(path) defer file.Close() if err != nil { fmt.Println(err) } } } _logger = log.New() //_logger.Formatter = new(log.JSONFormatter) _logger.Formatter = new(log.TextFormatter) _logger.Hooks.Add(lfshook.NewHook(logLevelFilePathMap)) return _logger }
func setupLogger() { logger.Hooks.Add(lfshook.NewHook(lfshook.PathMap{ logrus.ErrorLevel: config.Logfile, })) }
func main() { authFunc := func(username, password string) bool { log.WithFields(log.Fields{"username": username, "password": "******"}).Debug("main::authFunc Authentication requested") return true } logLevel := flag.String("ll", "Info", "Minimum log level. Available values are Debug, Info, Warn, Error") azureAccount := flag.String("an", "", "Azure blob storage account name") azureKey := flag.String("ak", "", "Azure blob storage account key (either primary or secondary)") localFSRoot := flag.String("lfs", "", "Local file system root") tlsCertFile := flag.String("crt", "", "TLS certificate file") tlsKeyFile := flag.String("key", "", "TLS certificate key file") plainCmdPort := flag.Int("plainPort", 21, "Plain FTP port (unencrypted). If you specify a TLS certificate and key encryption you can pass -1 to start a SFTP implicit server only") encrCmdPort := flag.Int("tlsPort", 990, "Encrypted FTP port. If you do not specify a TLS certificate this port is ignored. If you specify -1 the implicit SFTP is disabled") lowerPort := flag.Int("minPasvPort", 50000, "Lower passive port range") higerPort := flag.Int("maxPasvPort", 50100, "Higher passive port range") logFileDebug := flag.String("lDebug", "", "Debug level log file") logFileInfo := flag.String("lInfo", "", "Info level log file") logFileWarn := flag.String("lWarn", "", "Warn level log file") logFileError := flag.String("lError", "", "Error level log file") flag.Parse() if *logFileDebug != "" || *logFileInfo != "" || *logFileWarn != "" || *logFileError != "" { log.AddHook(lfshook.NewHook(lfshook.PathMap{ log.DebugLevel: *logFileDebug, log.InfoLevel: *logFileInfo, log.WarnLevel: *logFileWarn, log.ErrorLevel: *logFileError, })) } if (*azureAccount == "" || *azureKey == "") && *localFSRoot == "" { log.Error("main::main must specify either a local file system root or a azure account (both name and key) as storage. Check the command line docs for help") os.Exit(-1) } switch strings.ToLower(*logLevel) { case "debug": log.SetLevel(log.DebugLevel) case "info": log.SetLevel(log.InfoLevel) case "warn": log.SetLevel(log.WarnLevel) case "error": log.SetLevel(log.ErrorLevel) default: log.WithFields(log.Fields{"logLevel": logLevel}).Error("main::main unsupported log level") os.Exit(-1) } log.WithField("program", os.Args[0]).Info("Program started") var fs fs.FileProvider var err error var cert tls.Certificate if *tlsCertFile != "" && *tlsKeyFile != "" { cert, err = tls.LoadX509KeyPair(*tlsCertFile, *tlsKeyFile) if err != nil { panic(err) } } if *azureAccount != "" && *azureKey != "" { log.WithFields(log.Fields{"account": *azureAccount}).Info("main::main initializating Azure blob storage backend") fs, err = azureFS.New(*azureAccount, *azureKey) } else { log.WithFields(log.Fields{"localFSRoot": *localFSRoot}).Info("main::main initializating local fs backend") fs, err = localFS.New(*localFSRoot) } if err != nil { panic(err) } // 15 min connection timeout timeout, err := time.ParseDuration("15m") if err != nil { panic(err) } var srv *ftp.Server if *tlsCertFile != "" && *tlsKeyFile != "" { if *encrCmdPort == -1 { srv = ftp.NewTLS(*plainCmdPort, &cert, timeout, *lowerPort, *higerPort, authFunc, fs) } else { srv = ftp.New(*plainCmdPort, *encrCmdPort, &cert, timeout, *lowerPort, *higerPort, authFunc, fs) } } else { srv = ftp.NewPlain(*plainCmdPort, nil, timeout, *lowerPort, *higerPort, authFunc, fs) } srv.Accept() signal_chan := make(chan os.Signal, 1) var code int signal.Notify(signal_chan) for { s := <-signal_chan switch s { case syscall.SIGINT: log.WithFields(log.Fields{"signal": "SIGINT"}).Warn("main::main " + s.String()) code = 0 case syscall.SIGTERM: log.WithFields(log.Fields{"signal": "SIGTERM"}).Warn("main::main " + s.String()) code = 0 case syscall.SIGPIPE: log.WithFields(log.Fields{"signal": "SIGPIPE"}).Warn("main::main " + s.String()) continue default: log.Error("main::main Unknown signal (" + s.String() + ")") code = 1 } break } os.Exit(code) }