当前位置: 首页>>代码示例>>Golang>>正文


Golang logrus.Logger类代码示例

本文整理汇总了Golang中github.com/Sirupsen/logrus.Logger的典型用法代码示例。如果您正苦于以下问题:Golang Logger类的具体用法?Golang Logger怎么用?Golang Logger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Logger类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: create

func (command HelloWorldResource) create(session *session.Session,
	logger *logrus.Logger) (map[string]interface{}, error) {
	logger.Info("create: Hello ", command.Message)
	return map[string]interface{}{
		"Resource": "Created message: " + command.Message,
	}, nil
}
开发者ID:mweagle,项目名称:cloudformationresources,代码行数:7,代码来源:helloWorldResource.go

示例2: userDefinedCustomResourceForwarder

func userDefinedCustomResourceForwarder(customResource *customResourceInfo,
	event *json.RawMessage,
	context *LambdaContext,
	w http.ResponseWriter,
	logger *logrus.Logger) {

	var rawProps map[string]interface{}
	json.Unmarshal([]byte(*event), &rawProps)

	var lambdaEvent cloudformationresources.CloudFormationLambdaEvent
	jsonErr := json.Unmarshal([]byte(*event), &lambdaEvent)
	if jsonErr != nil {
		logger.WithFields(logrus.Fields{
			"RawEvent":       rawProps,
			"UnmarshalError": jsonErr,
		}).Warn("Raw event data")
		http.Error(w, jsonErr.Error(), http.StatusInternalServerError)
	}

	logger.WithFields(logrus.Fields{
		"LambdaEvent": lambdaEvent,
	}).Debug("CloudFormation user resource lambda event")

	// Create the new request and send it off
	customResourceRequest := &cloudformationresources.UserFuncResourceRequest{}
	customResourceRequest.LambdaHandler = func(requestType string,
		stackID string,
		properties map[string]interface{},
		logger *logrus.Logger) (map[string]interface{}, error) {

		//  Descend to get the "UserProperties" field iff defined by the customResource
		var userProperties map[string]interface{}
		if _, exists := lambdaEvent.ResourceProperties["UserProperties"]; exists {
			childProps, ok := lambdaEvent.ResourceProperties["UserProperties"].(map[string]interface{})
			if !ok {
				return nil, fmt.Errorf("Failed to extract UserProperties from payload")
			}
			userProperties = childProps
		}
		return customResource.userFunction(requestType, stackID, userProperties, logger)
	}
	customResourceRequest.RequestType = lambdaEvent.RequestType
	customResourceRequest.ResponseURL = lambdaEvent.ResponseURL
	customResourceRequest.StackID = lambdaEvent.StackID
	customResourceRequest.RequestID = lambdaEvent.RequestID
	customResourceRequest.LogicalResourceID = lambdaEvent.LogicalResourceID
	customResourceRequest.PhysicalResourceID = lambdaEvent.PhysicalResourceID
	customResourceRequest.LogGroupName = context.LogGroupName
	customResourceRequest.LogStreamName = context.LogStreamName
	customResourceRequest.ResourceProperties = lambdaEvent.ResourceProperties
	if "" == customResourceRequest.PhysicalResourceID {
		customResourceRequest.PhysicalResourceID = fmt.Sprintf("LogStreamName: %s", context.LogStreamName)
	}
	requestErr := cloudformationresources.Run(customResourceRequest, logger)
	if requestErr != nil {
		http.Error(w, requestErr.Error(), http.StatusInternalServerError)
	} else {
		fmt.Fprint(w, "CustomResource handled: "+lambdaEvent.LogicalResourceID)
	}
}
开发者ID:mweagle,项目名称:Sparta,代码行数:60,代码来源:execute_utils.go

示例3: newInstanceCleaner

func newInstanceCleaner(
	cs *compute.Service,
	log *logrus.Logger,
	rateLimiter ratelimit.RateLimiter,
	rateLimitMaxCalls uint64,
	rateLimitDuration time.Duration,
	cutoffTime time.Time,
	projectID string,
	filters []string,
	noop bool,
) *instanceCleaner {
	return &instanceCleaner{
		cs:  cs,
		log: log.WithField("component", "instance_cleaner"),

		projectID: projectID,
		filters:   filters,

		noop: noop,

		CutoffTime: cutoffTime,

		rateLimiter:       rateLimiter,
		rateLimitMaxCalls: rateLimitMaxCalls,
		rateLimitDuration: rateLimitDuration,
	}
}
开发者ID:travis-ci,项目名称:gcloud-cleanup,代码行数:27,代码来源:instance_cleaner.go

示例4: LogrusLogger

// LogrusLogger is a middleware that will log each request recieved, along with
// some useful information, to the given logger.
func LogrusLogger(logger *logrus.Logger, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		entry := logger.WithFields(logrus.Fields{
			"request": r.RequestURI,
			"method":  r.Method,
			"remote":  r.RemoteAddr,
		})

		if id := r.Header.Get(RequestIDKey); id != "" {
			entry = entry.WithField("request_id", id)
		}

		// Wrap the writer so we can track data information.
		neww := WrapWriter(w)

		// Dispatch to the underlying handler.
		entry.Info("started handling request")
		h.ServeHTTP(neww, r)

		// Log final information.
		entry.WithFields(logrus.Fields{
			"bytes_written": neww.BytesWritten(),
			"status":        neww.Status(),
			"text_status":   http.StatusText(neww.Status()),
			"took":          time.Since(start),
		}).Info("completed handling request")
	}

	return http.HandlerFunc(fn)
}
开发者ID:jmptrader,项目名称:go-webapp-skeleton,代码行数:33,代码来源:logger.go

示例5: Main

// Main is the top of the pile.  Start here.
func Main(log *logrus.Logger) {
	opts := NewOptions()
	if opts.Debug {
		log.Level = logrus.DebugLevel
	}

	if opts.FileStorePrefix == "" {
		opts.FileStorePrefix = "tmp"
	}

	server, err := NewServer(opts, log, nil)
	if err != nil {
		log.Fatal(err)
	}

	port := os.Getenv("PORT")
	if port == "" {
		port = "9839"
	}

	addr := fmt.Sprintf(":%s", port)
	log.WithFields(logrus.Fields{
		"addr": addr,
	}).Info("artifacts-service listening")

	server.Run(addr)
}
开发者ID:hamfist,项目名称:artifacts-service,代码行数:28,代码来源:server.go

示例6: annotateDiscoveryInfo

func annotateDiscoveryInfo(template *gocf.Template, logger *logrus.Logger) *gocf.Template {
	for eachResourceID, eachResource := range template.Resources {
		// Only apply this to lambda functions
		if eachResource.Properties.CfnResourceType() == "AWS::Lambda::Function" {

			// Update the metdata with a reference to the output of each
			// depended on item...
			for _, eachDependsKey := range eachResource.DependsOn {
				dependencyOutputs, _ := outputsForResource(template, eachDependsKey, logger)
				if nil != dependencyOutputs && len(dependencyOutputs) != 0 {
					logger.WithFields(logrus.Fields{
						"Resource":  eachDependsKey,
						"DependsOn": eachResource.DependsOn,
						"Outputs":   dependencyOutputs,
					}).Debug("Resource metadata")
					safeMetadataInsert(eachResource, eachDependsKey, dependencyOutputs)
				}
			}
			// Also include standard AWS outputs at a resource level if a lambda
			// needs to self-discover other resources
			safeMetadataInsert(eachResource, TagLogicalResourceID, gocf.String(eachResourceID))
			safeMetadataInsert(eachResource, TagStackRegion, gocf.Ref("AWS::Region"))
			safeMetadataInsert(eachResource, TagStackID, gocf.Ref("AWS::StackId"))
			safeMetadataInsert(eachResource, TagStackName, gocf.Ref("AWS::StackName"))
		}
	}
	return template
}
开发者ID:mweagle,项目名称:Sparta,代码行数:28,代码来源:provision.go

示例7: NewServer

// NewServer creates a new *Server with a router and its routes registered
func NewServer(opts *Options, log *logrus.Logger, md metadata.LookupSaver) (*Server, error) {
	var err error

	log.Debug("creating new server")
	srv := &Server{
		opts: opts,
		log:  log,
	}

	srv.setupRouter()
	srv.setupNegroni()

	err = srv.getMd(md)
	if err != nil {
		return nil, err
	}

	err = srv.setupStorer()
	if err != nil {
		return nil, err
	}

	err = srv.setupAuther()
	if err != nil {
		return nil, err
	}

	return srv, nil
}
开发者ID:hamfist,项目名称:artifacts-service,代码行数:30,代码来源:server.go

示例8: validateSpartaPreconditions

func validateSpartaPreconditions(lambdaAWSInfos []*LambdaAWSInfo, logger *logrus.Logger) error {
	var errorText []string
	collisionMemo := make(map[string]string, 0)

	// 1 - check for duplicate golang function references.
	for _, eachLambda := range lambdaAWSInfos {
		testName := eachLambda.lambdaFnName
		if _, exists := collisionMemo[testName]; !exists {
			collisionMemo[testName] = testName
			// We'll always find our own lambda
			duplicateCount := 0
			for _, eachCheckLambda := range lambdaAWSInfos {
				if testName == eachCheckLambda.lambdaFnName {
					duplicateCount++
				}
			}
			// We'll always find our own lambda
			if duplicateCount > 1 {
				logger.WithFields(logrus.Fields{
					"CollisionCount": duplicateCount,
					"Name":           testName,
				}).Error("Detected Sparta lambda function associated with multiple LambdaAWSInfo structs")
				errorText = append(errorText, fmt.Sprintf("Multiple definitions of lambda: %s", testName))
			}
		}
	}
	if len(errorText) != 0 {
		return errors.New(strings.Join(errorText[:], "\n"))
	}
	return nil
}
开发者ID:conikeec,项目名称:Sparta,代码行数:31,代码来源:sparta.go

示例9: NewMesosLib

func NewMesosLib(master string, log *logrus.Logger, frameworkInfo *mesosproto.FrameworkInfo, ip string, port int) *MesosLib {
	m := &MesosLib{
		Log:           log,
		master:        master,
		frameworkInfo: frameworkInfo,
		ip:            ip,
		port:          port,
		Router:        mux.NewRouter(),
		events: events{
			mesosproto.Event_REGISTERED: make(chan *mesosproto.Event, 64),
			mesosproto.Event_OFFERS:     make(chan *mesosproto.Event, 64),
			mesosproto.Event_UPDATE:     make(chan *mesosproto.Event, 64),
		},
	}

	if m.ip == "" {
		name, err := os.Hostname()
		if err != nil {
			log.Fatalf("Failed to get hostname: %+v", err)
		}

		addrs, err := net.LookupHost(name)
		if err != nil {
			log.Fatalf("Failed to get address for hostname %q: %+v", name, err)
		}

		for _, addr := range addrs {
			if m.ip == "" || !strings.HasPrefix(addr, "127") {
				m.ip = addr
			}
		}
	}
	m.initAPI()
	return m
}
开发者ID:ruo91,项目名称:volt,代码行数:35,代码来源:mesoslib.go

示例10: SetupLogger

func SetupLogger(logger *logrus.Logger) {
	fmter := &prefixed.TextFormatter{}
	logger.Formatter = fmter
	logger.Out = os.Stdout
	// Only log the info severity or above.
	logger.Level = logrus.InfoLevel
}
开发者ID:hobeone,项目名称:rss2go,代码行数:7,代码来源:log.go

示例11: LogError

func LogError(r *http.Request, err error, info string, logger *log.Logger) {
	logger.WithFields(log.Fields{
		"error":  err.Error(),
		"method": r.Method,
		"url":    r.URL.String(),
	}).Error(info)
}
开发者ID:jeff235255,项目名称:forum,代码行数:7,代码来源:log_template.go

示例12: stackLambdaResources

func stackLambdaResources(serviceName string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (provisionedResources, error) {

	resources := make(provisionedResources, 0)
	nextToken := ""
	for {
		params := &cloudformation.ListStackResourcesInput{
			StackName: aws.String(serviceName),
		}
		if "" != nextToken {
			params.NextToken = aws.String(nextToken)
		}
		resp, err := cf.ListStackResources(params)

		if err != nil {
			logger.Error(err.Error())
			return nil, err
		}
		for _, eachSummary := range resp.StackResourceSummaries {
			if *eachSummary.ResourceType == "AWS::Lambda::Function" {
				resources = append(resources, eachSummary)
			}
		}
		if nil != resp.NextToken {
			nextToken = *resp.NextToken
		} else {
			break
		}
	}
	return resources, nil
}
开发者ID:seiffert,项目名称:Sparta,代码行数:30,代码来源:explore.go

示例13: StackExists

// StackExists returns whether the given stackName or stackID currently exists
func StackExists(stackNameOrID string, awsSession *session.Session, logger *logrus.Logger) (bool, error) {
	cf := cloudformation.New(awsSession)

	describeStacksInput := &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackNameOrID),
	}
	describeStacksOutput, err := cf.DescribeStacks(describeStacksInput)
	logger.WithFields(logrus.Fields{
		"DescribeStackOutput": describeStacksOutput,
	}).Debug("DescribeStackOutput results")

	exists := false
	if err != nil {
		logger.WithFields(logrus.Fields{
			"DescribeStackOutputError": err,
		}).Debug("DescribeStackOutput")

		// If the stack doesn't exist, then no worries
		if strings.Contains(err.Error(), "does not exist") {
			exists = false
		} else {
			return false, err
		}
	} else {
		exists = true
	}
	return exists, nil
}
开发者ID:mweagle,项目名称:Sparta,代码行数:29,代码来源:util.go

示例14: NewWithNameAndLogger

// NewWithNameAndLogger returns a new middleware handler with the specified name
// and logger
func NewWithNameAndLogger(name string, l *logrus.Logger) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			start := time.Now()

			entry := l.WithFields(logrus.Fields{
				"request": c.Request().RequestURI,
				"method":  c.Request().Method,
				"remote":  c.Request().RemoteAddr,
			})

			if reqID := c.Request().Header.Get("X-Request-Id"); reqID != "" {
				entry = entry.WithField("request_id", reqID)
			}

			entry.Info("started handling request")

			if err := next(c); err != nil {
				c.Error(err)
			}

			latency := time.Since(start)

			entry.WithFields(logrus.Fields{
				"status":      c.Response().Status(),
				"text_status": http.StatusText(c.Response().Status()),
				"took":        latency,
				fmt.Sprintf("measure#%s.latency", name): latency.Nanoseconds(),
			}).Info("completed handling request")

			return nil
		}
	}
}
开发者ID:psihodelik,项目名称:echo-logrus,代码行数:36,代码来源:logger.go

示例15: safeMergeTemplates

func safeMergeTemplates(sourceTemplate *gocf.Template, destTemplate *gocf.Template, logger *logrus.Logger) error {
	var mergeErrors []string

	// Append the custom resources
	for eachKey, eachLambdaResource := range sourceTemplate.Resources {
		_, exists := destTemplate.Resources[eachKey]
		if exists {
			errorMsg := fmt.Sprintf("Duplicate CloudFormation resource name: %s", eachKey)
			mergeErrors = append(mergeErrors, errorMsg)
		} else {
			destTemplate.Resources[eachKey] = eachLambdaResource
		}
	}
	// Append the custom outputs
	for eachKey, eachLambdaOutput := range sourceTemplate.Outputs {
		_, exists := destTemplate.Outputs[eachKey]
		if exists {
			errorMsg := fmt.Sprintf("Duplicate CloudFormation output key name: %s", eachKey)
			mergeErrors = append(mergeErrors, errorMsg)
		} else {
			destTemplate.Outputs[eachKey] = eachLambdaOutput
		}
	}
	if len(mergeErrors) > 0 {
		logger.Error("Failed to update template. The following collisions were found:")
		for _, eachError := range mergeErrors {
			logger.Error("\t" + eachError)
		}
		return errors.New("Template merge failed")
	}
	return nil
}
开发者ID:conikeec,项目名称:Sparta,代码行数:32,代码来源:cloudformation_resources.go


注:本文中的github.com/Sirupsen/logrus.Logger类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。