本文整理汇总了Golang中github.com/Sirupsen/logrus.SetOutput函数的典型用法代码示例。如果您正苦于以下问题:Golang SetOutput函数的具体用法?Golang SetOutput怎么用?Golang SetOutput使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetOutput函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Connect
func Connect() bool {
success := false
logrus.SetFormatter(&logrus.JSONFormatter{})
if !debugFlag {
logrus.SetOutput(ioutil.Discard)
} else {
logrus.SetOutput(os.Stdout)
}
if fluentdServer != "" {
host, port, err := net.SplitHostPort(fluentdServer)
if err != nil {
LogError(fmt.Sprintf("Unable to split to fluentd server [%s]!\n", fluentdServer), err.Error())
}
portInt, err := strconv.Atoi(port)
if err != nil {
LogError(fmt.Sprintf("Unable to convert port format [%s]!\n", port), err.Error())
}
hook := logrus_fluent.NewHook(host, portInt)
LogStd(fmt.Sprintf("Received hook to fluentd server [%s]!\n", fluentdServer), false)
logrus.AddHook(hook)
success = true
}
return success
}
示例2: init
func init() {
var cfgFile string
flag.StringVar(&cfgFile, "c", "myMon.cfg", "myMon configure file")
flag.Parse()
if _, err := os.Stat(cfgFile); err != nil {
if os.IsNotExist(err) {
log.WithField("cfg", cfgFile).Fatalf("myMon config file does not exists: %v", err)
}
}
if err := cfg.readConf(cfgFile); err != nil {
log.Fatalf("Read configure file failed: %v", err)
}
// Init log file
log.SetFormatter(&log.JSONFormatter{})
log.SetLevel(log.Level(cfg.LogLevel))
if cfg.LogFile != "" {
f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err == nil {
log.SetOutput(f)
return
}
}
log.SetOutput(os.Stderr)
}
示例3: initLogrus
func initLogrus(ctx *cli.Context) {
logrus.SetFormatter(&logrus.TextFormatter{
TimestampFormat: time.RFC822,
FullTimestamp: true,
})
if level, err := logrus.ParseLevel(ctx.String("log_level")); err == nil {
logrus.SetLevel(level)
} else {
log.Error(err)
logrus.SetLevel(logrus.InfoLevel)
}
filename := ctx.String("log_file")
logrus.SetOutput(os.Stderr)
if filename != "" {
var f *os.File
_, err := os.Stat(filename)
if !os.IsNotExist(err) {
os.Rename(filename, filename+".prev")
}
f, err = os.Create(filename)
if err != nil {
log.Error("Cannot create log file ", err)
log.Warning("Continuing to log to stderr")
} else {
logrus.SetOutput(f)
}
}
}
示例4: daemonEnvironmentSetup
func daemonEnvironmentSetup(c *cli.Context) error {
var err error
root := c.String("root")
if root == "" {
return fmt.Errorf("Have to specific root directory")
}
if err := util.MkdirIfNotExists(root); err != nil {
return fmt.Errorf("Invalid root directory:", err)
}
lockPath := filepath.Join(root, LOCKFILE)
if lockFile, err = util.LockFile(lockPath); err != nil {
return fmt.Errorf("Failed to lock the file at %v: %v", lockPath, err.Error())
}
logrus.SetLevel(logrus.DebugLevel)
logName := c.String("log")
if logName != "" {
logFile, err := os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return err
}
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetOutput(logFile)
} else {
logrus.SetOutput(os.Stdout)
}
return nil
}
示例5: main
func main() {
// Log as JSON instead of the default ASCII formatter.
// log.SetFormatter(&log.JSONFormatter{})
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
// log.AddHook(&logrus_airbrake.AirbrakeHook{})
setlogfile := false
if setlogfile {
// backendlog := logging.NewLogBackend(os.Stderr, "", 0)
f, err := os.OpenFile("cdr-pusher.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err.Error())
}
defer f.Close()
// Output to stderr instead of stdout, could also be a file.
log.SetOutput(f)
} else {
log.SetOutput(os.Stderr)
}
// Only log the warning severity or above.
// log.SetLevel(log.WarnLevel)
log.SetLevel(log.InfoLevel)
// log.SetLevel(log.DebugLevel)
log.Info("StartTime: " + time.Now().Format("Mon Jan _2 2006 15:04:05"))
RunApp()
log.Info("StopTime: " + time.Now().Format("Mon Jan _2 2006 15:04:05"))
}
示例6: InitializeLogging
func InitializeLogging(config *LoggingConfig, useStd bool, level string) {
var lvl = log.DebugLevel
var e error
if level != "" {
lvl, e = log.ParseLevel(level)
} else if config.Level != "" {
lvl, e = log.ParseLevel(config.Level)
}
if nil != e {
lvl = log.DebugLevel
}
if useStd {
log.SetOutput(os.Stdout)
OUTPUT_FILE = nil
} else {
f, e := os.OpenFile(config.Filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if nil != e {
fmt.Errorf("Open file <%s> for logging failed<%v>!\n", config.Filename, e)
} else {
log.SetOutput(f)
OUTPUT_FILE = f
}
}
if strings.ToLower(config.Format) == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else {
log.SetFormatter(&PlainFormatter{})
}
log.SetLevel(lvl)
//log.Info("Logging Initialized.")
}
示例7: configureLogging
func configureLogging(v *viper.Viper) {
level, err := log.ParseLevel(v.GetString("log_level"))
if err != nil {
log.Fatalln(err)
}
log.SetLevel(level)
if v.GetString("log_format") == "text" {
log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true})
} else if v.GetString("log_format") == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else {
log.Errorln("Error: log_type invalid, defaulting to text")
log.SetFormatter(&log.TextFormatter{})
}
switch v.GetString("log_target") {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
log.SetOutput(os.Stderr)
default:
log.Errorln("Error: log_target invalid, defaulting to Stdout")
log.SetOutput(os.Stdout)
}
}
示例8: TestRunWithTimeoutFailed
func TestRunWithTimeoutFailed(t *testing.T) {
log.SetLevel(log.DebugLevel)
defer log.SetLevel(log.InfoLevel)
tmp, _ := ioutil.TempFile("", "tmp")
defer os.Remove(tmp.Name())
log.SetOutput(tmp)
defer log.SetOutput(os.Stdout)
cmd, _ := NewCommand("./testdata/test.sh failStuff --debug", "100ms")
fields := log.Fields{"process": "test"}
if err := RunWithTimeout(cmd, fields); err == nil {
t.Errorf("Expected error but got nil")
}
time.Sleep(200 * time.Millisecond)
buf, _ := ioutil.ReadFile(tmp.Name())
logs := string(buf)
if strings.Contains(logs, "timeout after") {
t.Fatalf("RunWithTimeout failed to cancel timeout after failure: %v", logs)
}
}
示例9: Connect
func Connect() bool {
success := false
logrus.SetFormatter(&logrus.JSONFormatter{})
if !debugFlag {
logrus.SetOutput(ioutil.Discard)
} else {
logrus.SetOutput(os.Stdout)
}
if syslogServer != "" {
hook, err := logrus_syslog.NewSyslogHook("tcp", syslogServer, syslog.LOG_INFO, "doppler")
if err != nil {
LogError(fmt.Sprintf("Unable to connect to syslog server [%s]!\n", syslogServer), err.Error())
} else {
LogStd(fmt.Sprintf("Received hook to syslog server [%s]!\n", syslogServer), false)
logrus.AddHook(hook)
success = true
}
}
return success
}
示例10: logAction
func logAction(sl string) {
if strings.HasPrefix(sl, "log on") {
*logDump = "on"
log.SetOutput(multi_writer)
} else if strings.HasPrefix(sl, "log off") {
*logDump = "off"
log.SetOutput(os.Stderr)
} else if strings.HasPrefix(sl, "log show") {
// TODO: send all the saved log to websocket
//h.broadcastSys <- []byte("{\"BufFlowDebug\" : \"" + *logDump + "\"}")
}
}
示例11: Test_log_functions_panic_logger
func Test_log_functions_panic_logger(t *testing.T) {
a := assert.New(t)
w := bytes.NewBuffer([]byte{})
log.SetOutput(w)
defer log.SetOutput(os.Stderr)
raisePanic()
a.Contains(w.String(), "PANIC")
a.Contains(w.String(), "raisePanic")
a.Contains(w.String(), "Don't panic!")
}
示例12: InitLog
func InitLog(cfg *Cfg) {
// Init log file
log.SetFormatter(&log.JSONFormatter{})
log.SetLevel(log.Level(cfg.LogLevel))
if cfg.LogFile != "" {
f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err == nil {
log.SetOutput(f)
return
}
}
log.SetOutput(os.Stderr)
}
示例13: Test
// Test run callable with changed logging output
func Test(callable func(*bytes.Buffer)) {
buf := &bytes.Buffer{}
logrus.SetOutput(buf)
callable(buf)
var loggerOut io.Writer
if std.fd != nil {
loggerOut = std.fd
} else {
loggerOut = os.Stderr
}
logrus.SetOutput(loggerOut)
}
示例14: parseConfig
func parseConfig() *viper.Viper {
if verbose {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(os.Stderr)
}
// Get home directory for current user
homeDir, err := homedir.Dir()
if err != nil {
fatalf("Cannot get current user home directory: %v", err)
}
if homeDir == "" {
fatalf("Cannot get current user home directory")
}
// By default our trust directory (where keys are stored) is in ~/.notary/
mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir)))
// If there was a commandline configFile set, we parse that.
// If there wasn't we attempt to find it on the default location ~/.notary/config
if configFile != "" {
configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".")
configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile))
configPath = filepath.Dir(configFile)
} else {
configPath = filepath.Join(homeDir, filepath.Dir(configDir))
}
// Setup the configuration details into viper
mainViper.SetConfigName(configFileName)
mainViper.SetConfigType(configFileExt)
mainViper.AddConfigPath(configPath)
// Find and read the config file
err = mainViper.ReadInConfig()
if err != nil {
logrus.Debugf("Configuration file not found, using defaults")
// If we were passed in a configFile via -c, bail if it doesn't exist,
// otherwise ignore it: we can use the defaults
if configFile != "" || !os.IsNotExist(err) {
fatalf("error opening config file %v", err)
}
}
// At this point we either have the default value or the one set by the config.
// Either way, the command-line flag has precedence and overwrites the value
if trustDir != "" {
mainViper.Set("trust_dir", trustDir)
}
// Expands all the possible ~/ that have been given, either through -d or config
// If there is no error, use it, if not, attempt to use whatever the user gave us
expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir"))
if err == nil {
mainViper.Set("trust_dir", expandedTrustDir)
}
logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir"))
return mainViper
}
示例15: init
func init() {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
TimestampFormat: "15:04:05",
})
log.SetOutput(os.Stdout)
}