本文整理汇总了Golang中github.com/Sirupsen/logrus.StandardLogger函数的典型用法代码示例。如果您正苦于以下问题:Golang StandardLogger函数的具体用法?Golang StandardLogger怎么用?Golang StandardLogger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了StandardLogger函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: pullCommand
func pullCommand(c *cli.Context) {
args := c.Args()
if len(args) < 1 {
log.Fatal("rocker pull <image>")
}
dockerClient, err := dockerclient.NewFromCli(c)
if err != nil {
log.Fatal(err)
}
cacheDir, err := util.MakeAbsolute(c.String("cache-dir"))
if err != nil {
log.Fatal(err)
}
options := build.DockerClientOptions{
Client: dockerClient,
Auth: initAuth(c),
Log: log.StandardLogger(),
S3storage: s3.New(dockerClient, cacheDir),
StdoutContainerFormatter: log.StandardLogger().Formatter,
StderrContainerFormatter: log.StandardLogger().Formatter,
}
client := build.NewDockerClient(options)
if err := client.PullImage(args[0]); err != nil {
log.Fatal(err)
}
}
示例2: main
func main() {
flag.Parse()
// connect with the logging server
if logger != "" && (amroot || debug) {
// blocks until we can connect to the logger
lh, err := logutils.NewLoggerHook(logger, hostname, app)
if err != nil {
log.WithFields(log.Fields{
"file": logutils.File(),
}).Fatalln("ERROR SETTING UP LOGGING SERVER:", err)
}
log.AddHook(lh)
}
//log.Println("IN FORKEXEC")
////log.SetOutput(ioutil.Discard)
////log.Println("Log Test")
////fmt.Println("exiting logger block")
//}
// log.Println("IN FORK EXEC")
// recombine the flags for exec to use
args := []string{
"-failures=" + strconv.Itoa(failures),
"-rfail=" + strconv.Itoa(rFail),
"-ffail=" + strconv.Itoa(fFail),
"-hostname=" + hostname,
"-config=" + configFile,
"-logger=" + logger,
"-app=" + app,
"-pprof=" + pprofaddr,
"-physaddr=" + physaddr,
"-rootwait=" + strconv.Itoa(rootwait),
"-debug=" + strconv.FormatBool(debug),
"-rounds=" + strconv.Itoa(rounds),
"-amroot=" + strconv.FormatBool(amroot),
"-test_connect=" + strconv.FormatBool(testConnect),
"-suite=" + suite,
}
cmd := exec.Command("./exec", args...)
cmd.Stdout = log.StandardLogger().Writer()
cmd.Stderr = log.StandardLogger().Writer()
// log.Println("running command:", cmd)
err := cmd.Run()
if err != nil {
log.Errorln("cmd run:", err)
}
// get CPU usage stats
st := cmd.ProcessState.SystemTime()
ut := cmd.ProcessState.UserTime()
log.WithFields(log.Fields{
"file": logutils.File(),
"type": "forkexec",
"systime": st,
"usertime": ut,
}).Info("")
}
示例3: CmdImport
func CmdImport(databaseName, filePath, mongoCollection, mongoDatabase string, id IDb, is services.IServices, ij jobs.IJobs) error {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return fmt.Errorf("A file does not exist at path '%s'", filePath)
}
service, err := is.RetrieveByLabel(databaseName)
if err != nil {
return err
}
if service == nil {
return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", databaseName)
}
logrus.Printf("Backing up \"%s\" before performing the import", databaseName)
job, err := id.Backup(service)
if err != nil {
return err
}
logrus.Printf("Backup started (job ID = %s)", job.ID)
// all because logrus treats print, println, and printf the same
logrus.StandardLogger().Out.Write([]byte("Polling until backup finishes."))
status, err := ij.PollTillFinished(job.ID, service.ID)
if err != nil {
return err
}
job.Status = status
logrus.Printf("\nEnded in status '%s'", job.Status)
err = id.DumpLogs("backup", job, service)
if err != nil {
return err
}
if job.Status != "finished" {
return fmt.Errorf("Job finished with invalid status %s", job.Status)
}
logrus.Printf("Importing '%s' into %s (ID = %s)", filePath, databaseName, service.ID)
job, err = id.Import(filePath, mongoCollection, mongoDatabase, service)
if err != nil {
return err
}
// all because logrus treats print, println, and printf the same
logrus.StandardLogger().Out.Write([]byte(fmt.Sprintf("Processing import (job ID = %s).", job.ID)))
status, err = ij.PollTillFinished(job.ID, service.ID)
if err != nil {
return err
}
job.Status = status
logrus.Printf("\nImport complete (end status = '%s')", job.Status)
err = id.DumpLogs("restore", job, service)
if err != nil {
return err
}
if job.Status != "finished" {
return fmt.Errorf("Finished with invalid status %s", job.Status)
}
return nil
}
示例4: init
func init() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, fmt.Sprintf(banner, version, os.Args[0]))
flag.PrintDefaults()
}
flag.BoolVar(&movie, "movie", false, "parse as movie file")
flag.BoolVar(&tv, "tv", false, "parse as TV file")
flag.BoolVar(&showVersion, "showVersion", false, "show showVersion and exit")
flag.StringVar(&format, "format", "", "output format")
flag.Parse()
filenames = flag.Args()
// Set debug level
if debug {
log.StandardLogger().Level = log.DebugLevel
} else {
log.StandardLogger().Level = log.ErrorLevel
}
if movie && tv {
fmt.Fprintln(os.Stderr, "Cannot use both -movie and -tv simultaneously")
flag.Usage()
os.Exit(1)
}
if !movie && !tv {
fmt.Fprintln(os.Stderr, "Please provide -movie or -tv")
flag.Usage()
os.Exit(1)
}
if showVersion {
fmt.Println(version)
os.Exit(0)
}
if len(filenames) == 0 {
fmt.Fprintln(os.Stderr, "No input provided")
flag.Usage()
os.Exit(1)
}
// Set default format if -format is omitted
if strings.Trim(format, " ") == "" {
if movie {
format = "{{spaces .Title | title | underscores}}.{{.Year}}.{{.Ext}}"
} else {
format = `{{spaces .Title | title | underscores}}.{{printf "%02d" .Season}}{{printf "%02d" .Episode}}.{{.Ext}}`
}
}
}
示例5: Start
func (m *mod) Start() error {
stdOut := log.StandardLogger().Writer()
stdErr := log.StandardLogger().Writer()
r := mux.NewRouter()
r.Handle("/r/module/instances",
handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleInstHandler)))
r.Handle("/r/module/instances/{id}/start",
handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleInstStartHandler)))
r.Handle("/r/module/types",
handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleTypeHandler)))
r.Handle("/images/rexray-banner-logo.svg",
handlers.LoggingHandler(stdOut, http.HandlerFunc(imagesHandler)))
r.Handle("/scripts/jquery-1.11.3.min.js",
handlers.LoggingHandler(stdOut, http.HandlerFunc(scriptsHandler)))
r.Handle("/styles/main.css",
handlers.LoggingHandler(stdOut, http.HandlerFunc(stylesHandler)))
r.Handle("/",
handlers.LoggingHandler(stdOut, http.HandlerFunc(indexHandler)))
_, addr, parseAddrErr := util.ParseAddress(m.Address())
if parseAddrErr != nil {
return parseAddrErr
}
s := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
ErrorLog: golog.New(stdErr, "", 0),
}
go func() {
defer stdOut.Close()
defer stdErr.Close()
sErr := s.ListenAndServe()
if sErr != nil {
panic(sErr)
}
}()
return nil
}
示例6: TestLogrusWithJsonFormatter
func TestLogrusWithJsonFormatter(t *testing.T) {
p := &Person{
Name: "Bruce",
Alias: "Batman",
Hideout: &Hideout{
Name: "JLU Tower",
DimensionId: 52,
},
}
log.SetFormatter(newJsonFormatter())
entry := log.NewEntry(log.StandardLogger())
entry.Message = "the dark knight"
entry.Data = log.Fields{"hero": p}
s, _ := entry.String()
if !strings.Contains(s, `"hero.name":"Bruce"`) {
t.Fatalf(`missing "hero.name":"Bruce"`)
}
if !strings.Contains(s, `"hero.alias":"Batman"`) {
t.Fatalf(`missing "hero.alias":"Batman"`)
}
if !strings.Contains(s, `"hero.hideout.name":"JLU Tower"`) {
t.Fatalf(`missing "hero.hideout.name":"JLU Tower"`)
}
if !strings.Contains(s, `"hero.hideout.dimensionId":52`) {
t.Fatalf(`missing "hero.hideout.dimensionId":52`)
}
}
示例7: Validate
// Validate validates the provided data (d) against the provided schema (s).
func Validate(ctx types.Context, s, d []byte) error {
if ctx == nil {
log.StandardLogger().WithFields(log.Fields{
"schema": string(s),
"body": string(d),
}).Debug("validating schema")
} else {
ctx.WithFields(log.Fields{
"schema": string(s),
"body": string(d),
}).Debug("validating schema")
}
validator, err := getSchemaValidator(s)
if err != nil {
return err
}
if len(d) == 0 {
d = []byte("{}")
}
data, err := ucl.Parse(bytes.NewReader(d))
if err != nil {
return err
}
return validator.Validate(data)
}
示例8: NewFeedWatcher
// NewFeedWatcher returns a new FeedWatcher instance.
func NewFeedWatcher(
feedInfo db.FeedInfo,
crawlChan chan *FeedCrawlRequest,
responseChan chan *FeedCrawlResponse,
mailChan chan *mail.Request,
dbh db.Service,
GUIDCache []string,
minSleep int64,
maxSleep int64,
) *FeedWatcher {
guids := map[string]bool{}
for _, i := range GUIDCache {
guids[i] = true
}
return &FeedWatcher{
FeedInfo: feedInfo,
exitChan: make(chan int),
crawlChan: crawlChan,
responseChan: responseChan,
mailerChan: mailChan,
polling: false,
crawling: false,
minSleepTime: time.Duration(minSleep) * time.Second,
maxSleepTime: time.Duration(maxSleep) * time.Second,
dbh: dbh,
GUIDCache: guids,
LastCrawlResponse: &FeedCrawlResponse{},
After: After,
Logger: logrus.StandardLogger(),
}
}
示例9: CmdBackup
func CmdBackup(databaseName string, skipPoll bool, id IDb, is services.IServices, ij jobs.IJobs) error {
service, err := is.RetrieveByLabel(databaseName)
if err != nil {
return err
}
if service == nil {
return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", databaseName)
}
job, err := id.Backup(service)
if err != nil {
return err
}
logrus.Printf("Backup started (job ID = %s)", job.ID)
if !skipPoll {
// all because logrus treats print, println, and printf the same
logrus.StandardLogger().Out.Write([]byte("Polling until backup finishes."))
status, err := ij.PollTillFinished(job.ID, service.ID)
if err != nil {
return err
}
job.Status = status
logrus.Printf("\nEnded in status '%s'", job.Status)
err = id.DumpLogs("backup", job, service)
if err != nil {
return err
}
if job.Status != "finished" {
return fmt.Errorf("Job finished with invalid status %s", job.Status)
}
}
logrus.Printf("You can download your backup with the \"catalyze db download %s %s ./output_file_path\" command", databaseName, job.ID)
return nil
}
示例10: configureSyslog
func configureSyslog(syslogParam string) {
var err error
var hook log.Hook
// disable colors if we're writing to syslog *and* we're the default text
// formatter, because the tty detection is useless here.
if tf, ok := log.StandardLogger().Formatter.(*log.TextFormatter); ok {
tf.DisableColors = true
}
if syslogParam == "kernel" {
hook, err = logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "netplugin")
if err != nil {
log.Fatalf("Could not connect to kernel syslog")
}
} else {
u, err := url.Parse(syslogParam)
if err != nil {
log.Fatalf("Could not parse syslog spec: %v", err)
}
hook, err = logrus_syslog.NewSyslogHook(u.Scheme, u.Host, syslog.LOG_INFO, "netplugin")
if err != nil {
log.Fatalf("Could not connect to syslog: %v", err)
}
}
log.AddHook(hook)
}
示例11: CmdList
func CmdList(is ISites, iservices services.IServices) error {
serviceProxy, err := iservices.RetrieveByLabel("service_proxy")
if err != nil {
return err
}
sites, err := is.List(serviceProxy.ID)
if err != nil {
return err
}
if sites == nil || len(*sites) == 0 {
logrus.Println("No sites found")
return nil
}
svcs, err := iservices.List()
svcMap := map[string]string{}
for _, s := range *svcs {
svcMap[s.ID] = s.Label
}
data := [][]string{{"NAME", "CERT", "UPSTREAM SERVICE"}}
for _, s := range *sites {
data = append(data, []string{s.Name, s.Cert, svcMap[s.UpstreamService]})
}
table := tablewriter.NewWriter(logrus.StandardLogger().Out)
table.SetBorder(false)
table.SetRowLine(false)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.AppendBulk(data)
table.Render()
return nil
}
示例12: main
func main() {
envflag.Parse()
if *debug {
logrus.SetLevel(logrus.DebugLevel)
} else {
logrus.SetLevel(logrus.WarnLevel)
}
handler := router.Load(
ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true),
middleware.Version,
middleware.Store(),
middleware.Remote(),
middleware.Cache(),
)
if *cert != "" {
logrus.Fatal(
http.ListenAndServeTLS(*addr, *cert, *key, handler),
)
} else {
logrus.Fatal(
http.ListenAndServe(*addr, handler),
)
}
}
示例13: init
func init() {
// 初始化日志
logrus.SetFormatter(&logrus.JSONFormatter{})
log.SetOutput(logrus.StandardLogger().Out)
// 初始化配置
Config = loadConfig()
lv, err := logrus.ParseLevel(Config.LogLevel)
if err != nil {
logrus.WithError(err).Warn("解析日志等级出错")
lv = logrus.DebugLevel
}
logrus.SetLevel(lv)
if Config.ReportOn {
hook, err := logrus_mail.NewMailAuthHook(Config.AppName,
Config.MailerHost,
Config.MailerPort,
Config.MailerUser,
Config.MailReceiver,
Config.MailerUser,
Config.MailerPass)
if err == nil {
logrus.AddHook(hook)
}
}
exeRoot := filepath.Dir(os.Args[0])
f, err := os.OpenFile(filepath.Join(exeRoot, "retask.log"), os.O_APPEND|os.O_CREATE, os.ModePerm)
if err != nil {
logrus.WithError(err).Fatal("打开日志文件失败")
}
logrus.SetOutput(f)
}
示例14: runServer
func runServer(neoURL string, port string, cacheDuration string, env string) {
if duration, durationErr := time.ParseDuration(cacheDuration); durationErr != nil {
log.Fatalf("Failed to parse cache duration string, %v", durationErr)
} else {
organisations.CacheControlHeader = fmt.Sprintf("max-age=%s, public", strconv.FormatFloat(duration.Seconds(), 'f', 0, 64))
}
conf := neoutils.ConnectionConfig{
BatchSize: 1024,
Transactional: false,
HTTPClient: &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 100,
},
Timeout: 1 * time.Minute,
},
BackgroundConnect: true,
}
db, err := neoutils.Connect(neoURL, &conf)
if err != nil {
log.Fatalf("Error connecting to neo4j %s", err)
}
organisations.OrganisationDriver = organisations.NewCypherDriver(db, env)
servicesRouter := mux.NewRouter()
// Healthchecks and standards first
servicesRouter.HandleFunc("/__health", v1a.Handler("PublicOrganisationsRead Healthchecks",
"Checks for accessing neo4j", organisations.HealthCheck()))
servicesRouter.HandleFunc("/__gtg", organisations.GoodToGo)
// Then API specific ones:
servicesRouter.HandleFunc("/organisations/{uuid}", organisations.GetOrganisation).Methods("GET")
servicesRouter.HandleFunc("/organisations/{uuid}", organisations.MethodNotAllowedHandler)
var monitoringRouter http.Handler = servicesRouter
monitoringRouter = httphandlers.TransactionAwareRequestLoggingHandler(log.StandardLogger(), monitoringRouter)
monitoringRouter = httphandlers.HTTPMetricsHandler(metrics.DefaultRegistry, monitoringRouter)
// The following endpoints should not be monitored or logged (varnish calls one of these every second, depending on config)
// The top one of these build info endpoints feels more correct, but the lower one matches what we have in Dropwizard,
// so it's what apps expect currently same as ping, the content of build-info needs more definition
//using http router here to be able to catch "/"
http.HandleFunc(status.PingPath, status.PingHandler)
http.HandleFunc(status.PingPathDW, status.PingHandler)
http.HandleFunc(status.BuildInfoPath, status.BuildInfoHandler)
http.HandleFunc(status.BuildInfoPathDW, status.BuildInfoHandler)
http.HandleFunc("/__gtg", organisations.GoodToGo)
http.Handle("/", monitoringRouter)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("Unable to start server: %v", err)
}
}
示例15: main
func main() {
flag.Parse()
ch, err := tchannel.NewChannel("ping", nil)
if err != nil {
log.Fatalf("channel did not create successfully: %v", err)
}
logger := log.StandardLogger()
worker := &worker{
channel: ch,
ringpop: ringpop.NewRingpop("ping-app", *hostport, ch, &ringpop.Options{
Logger: bark.NewLoggerFromLogrus(logger),
}),
logger: logger,
}
if err := worker.RegisterPong(); err != nil {
log.Fatalf("could not register pong handler: %v", err)
}
if err := worker.channel.ListenAndServe(*hostport); err != nil {
log.Fatalf("could not listen on given hostport: %v", err)
}
opts := new(ringpop.BootstrapOptions)
opts.File = *hostfile
if _, err := worker.ringpop.Bootstrap(opts); err != nil {
log.Fatalf("ringpop bootstrap failed: %v", err)
}
select {}
}