當前位置: 首頁>>代碼示例>>Golang>>正文


Golang v1.Logger類代碼示例

本文整理匯總了Golang中github.com/mgutz/logxi/v1.Logger的典型用法代碼示例。如果您正苦於以下問題:Golang Logger類的具體用法?Golang Logger怎麽用?Golang Logger使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Logger類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: InitializeCertAuthConfig

// InitializeCertAuthConfig sets up the command line options for creating a CA
func InitializeCertAuthConfig(logger log.Logger) error {

	viper.SetDefault("Bits", "4096")
	viper.SetDefault("Years", "10")
	viper.SetDefault("Organization", "kappa-ca")
	viper.SetDefault("Country", "USA")

	if initCmd.PersistentFlags().Lookup("bits").Changed {
		logger.Info("", "Bits", KeyBits)
		viper.Set("Bits", KeyBits)
	}
	if initCmd.PersistentFlags().Lookup("years").Changed {
		logger.Info("", "Years", Years)
		viper.Set("Years", Years)
	}
	if initCmd.PersistentFlags().Lookup("organization").Changed {
		logger.Info("", "Organization", Organization)
		viper.Set("Organization", Organization)
	}
	if initCmd.PersistentFlags().Lookup("country").Changed {
		logger.Info("", "Country", Country)
		viper.Set("Country", Country)
	}
	if initCmd.PersistentFlags().Lookup("hosts").Changed {
		logger.Info("", "Hosts", Hosts)
		viper.Set("Hosts", Hosts)
	}

	return nil
}
開發者ID:blacklabeldata,項目名稱:kappa,代碼行數:31,代碼來源:init-ca.go

示例2: CreateCertificateAuthority

// CreateCertificateAuthority generates a new CA
func CreateCertificateAuthority(logger log.Logger, key *rsa.PrivateKey, years int, org, country, hostList string) ([]byte, error) {

	// Generate subject key id
	logger.Info("Generating SubjectKeyID")
	subjectKeyID, err := GenerateSubjectKeyID(key)
	if err != nil {
		return nil, err
	}

	// Create serial number
	logger.Info("Generating Serial Number")
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, fmt.Errorf("failed to generate serial number: %s", err.Error())
	}

	// Create template
	logger.Info("Creating Certificate template")
	template := &x509.Certificate{
		IsCA: true,
		BasicConstraintsValid: true,
		SubjectKeyId:          subjectKeyID,
		SerialNumber:          serialNumber,
		Subject: pkix.Name{
			Country:      []string{country},
			Organization: []string{org},
		},
		PublicKeyAlgorithm: x509.RSA,
		SignatureAlgorithm: x509.SHA512WithRSA,
		NotBefore:          time.Now().Add(-600).UTC(),
		NotAfter:           time.Now().AddDate(years, 0, 0).UTC(),

		// see http://golang.org/pkg/crypto/x509/#KeyUsage
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		KeyUsage:    x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
	}

	// Associate hosts
	logger.Info("Adding Hosts to Certificate")
	hosts := strings.Split(hostList, ",")
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	// Create cert
	logger.Info("Generating Certificate")
	cert, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
	if err != nil {
		return nil, err
	}

	return cert, nil
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:59,代碼來源:keys.go

示例3: SavePrivateKey

// SavePrivateKey saves a PrivateKey in the PEM format.
func SavePrivateKey(logger log.Logger, key *rsa.PrivateKey, filename string) {
	logger.Info("Saving Private Key")
	pemfile, _ := os.Create(filename)
	pemkey := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key)}
	pem.Encode(pemfile, pemkey)
	pemfile.Close()
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:10,代碼來源:keys.go

示例4: SaveCertificateRequest

// SaveCertificateRequest saves a certificate in the PEM format.
func SaveCertificateRequest(logger log.Logger, cert []byte, filename string) {
	logger.Info("Saving Certificate Request")
	pemfile, _ := os.Create(filename)
	pemkey := &pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: cert}
	pem.Encode(pemfile, pemkey)
	pemfile.Close()
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:10,代碼來源:keys.go

示例5: newGCSBackend

// newGCSBackend constructs a Google Cloud Storage backend using a pre-existing
// bucket. Credentials can be provided to the backend, sourced
// from environment variables or a service account file
func newGCSBackend(conf map[string]string, logger log.Logger) (Backend, error) {

	bucketName := os.Getenv("GOOGLE_STORAGE_BUCKET")

	if bucketName == "" {
		bucketName = conf["bucket"]
		if bucketName == "" {
			return nil, fmt.Errorf("env var GOOGLE_STORAGE_BUCKET or configuration parameter 'bucket' must be set")
		}
	}

	// path to service account JSON file
	credentialsFile := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
	if credentialsFile == "" {
		credentialsFile = conf["credentials_file"]
		if credentialsFile == "" {
			return nil, fmt.Errorf("env var GOOGLE_APPLICATION_CREDENTIALS or configuration parameter 'credentials_file' must be set")
		}
	}

	client, err := storage.NewClient(
		context.Background(),
		option.WithServiceAccountFile(credentialsFile),
	)

	if err != nil {
		return nil, fmt.Errorf("error establishing storage client: '%v'", err)
	}

	// check client connectivity by getting bucket attributes
	_, err = client.Bucket(bucketName).Attrs(context.Background())
	if err != nil {
		return nil, fmt.Errorf("unable to access bucket '%s': '%v'", bucketName, err)
	}

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("physical/gcs: max_parallel set", "max_parallel", maxParInt)
		}
	}

	g := GCSBackend{
		bucketName: bucketName,
		client:     client,
		permitPool: NewPermitPool(maxParInt),
		logger:     logger,
	}

	return &g, nil
}
開發者ID:naunga,項目名稱:vault,代碼行數:59,代碼來源:gcs.go

示例6: SavePublicKey

// SavePublicKey saves a public key in the PEM format.
func SavePublicKey(logger log.Logger, key *rsa.PrivateKey, filename string) {
	logger.Info("Saving Public Key")
	pemfile, _ := os.Create(filename)
	bytes, _ := x509.MarshalPKIXPublicKey(key.PublicKey)

	pemkey := &pem.Block{
		Type:  "RSA PUBLIC KEY",
		Bytes: bytes}
	pem.Encode(pemfile, pemkey)
	pemfile.Close()
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:12,代碼來源:keys.go

示例7: newAzureBackend

// newAzureBackend constructs an Azure backend using a pre-existing
// bucket. Credentials can be provided to the backend, sourced
// from the environment, AWS credential files or by IAM role.
func newAzureBackend(conf map[string]string, logger log.Logger) (Backend, error) {

	container := os.Getenv("AZURE_BLOB_CONTAINER")
	if container == "" {
		container = conf["container"]
		if container == "" {
			return nil, fmt.Errorf("'container' must be set")
		}
	}

	accountName := os.Getenv("AZURE_ACCOUNT_NAME")
	if accountName == "" {
		accountName = conf["accountName"]
		if accountName == "" {
			return nil, fmt.Errorf("'accountName' must be set")
		}
	}

	accountKey := os.Getenv("AZURE_ACCOUNT_KEY")
	if accountKey == "" {
		accountKey = conf["accountKey"]
		if accountKey == "" {
			return nil, fmt.Errorf("'accountKey' must be set")
		}
	}

	client, err := storage.NewBasicClient(accountName, accountKey)

	if err != nil {
		return nil, fmt.Errorf("Failed to create Azure client: %v", err)
	}

	client.GetBlobService().CreateContainerIfNotExists(container, storage.ContainerAccessTypePrivate)

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("azure: max_parallel set", "max_parallel", maxParInt)
		}
	}

	a := &AzureBackend{
		container:  container,
		client:     client.GetBlobService(),
		logger:     logger,
		permitPool: NewPermitPool(maxParInt),
	}
	return a, nil
}
開發者ID:quixoten,項目名稱:vault,代碼行數:57,代碼來源:azure.go

示例8: NewCache

// NewCache returns a physical cache of the given size.
// If no size is provided, the default size is used.
func NewCache(b Backend, size int, logger log.Logger) *Cache {
	if size <= 0 {
		size = DefaultCacheSize
	}
	if logger.IsTrace() {
		logger.Trace("physical/cache: creating LRU cache", "size", size)
	}
	cache, _ := lru.New2Q(size)
	c := &Cache{
		backend: b,
		lru:     cache,
	}
	return c
}
開發者ID:quixoten,項目名稱:vault,代碼行數:16,代碼來源:cache.go

示例9: CreatePkiDirectories

// CreatePkiDirectories creates the directory structures for storing the public and private keys.
func CreatePkiDirectories(logger log.Logger, root string) error {
	pki := path.Join(root, "pki")

	// Create pki directory
	if err := os.MkdirAll(pki, os.ModeDir|0755); err != nil {
		logger.Warn("Could not create pki/ directory", "err", err.Error())
		return err
	}

	// Create public directory
	if err := os.MkdirAll(path.Join(pki, "public"), os.ModeDir|0755); err != nil {
		logger.Warn("Could not create pki/public/ directory", "err", err.Error())
		return err
	}

	// Create private directory
	if err := os.MkdirAll(path.Join(pki, "private"), os.ModeDir|0755); err != nil {
		logger.Warn("Could not create pki/private/ directory", "err", err.Error())
		return err
	}

	// Create reqs directory
	if err := os.MkdirAll(path.Join(pki, "reqs"), os.ModeDir|0755); err != nil {
		logger.Warn("Could not create pki/reqs/ directory", "err", err.Error())
		return err
	}

	return nil
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:30,代碼來源:keys.go

示例10: handleChannelRequests

func handleChannelRequests(logger log.Logger, channel ssh.Channel, requests <-chan *ssh.Request, system datamodel.System, user datamodel.User) {
	defer channel.Close()

	for req := range requests {
		if req.Type == "skl" {
			logger.Info("SKL request", "request", string(req.Payload))
			req.Reply(true, nil)
		} else {
			if req.WantReply {
				req.Reply(false, nil)
			}
		}
	}
}
開發者ID:pgrew,項目名稱:kappa,代碼行數:14,代碼來源:handler.go

示例11: InitializeNewCertConfig

// InitializeNewCertConfig sets up the command line options for creating a new certificate
func InitializeNewCertConfig(logger log.Logger) error {
	viper.SetDefault("Name", "localhost")
	viper.SetDefault("ForceOverwrite", "false")

	if newCertCmd.PersistentFlags().Lookup("name").Changed {
		logger.Info("", "Name", Name)
		viper.Set("Name", Name)
	}
	if newCertCmd.PersistentFlags().Lookup("overwrite").Changed {
		logger.Info("", "ForceOverwrite", ForceOverwrite)
		viper.Set("ForceOverwrite", ForceOverwrite)
	}

	return nil
}
開發者ID:blacklabeldata,項目名稱:kappa,代碼行數:16,代碼來源:new-cert.go

示例12: ReadPrivateKey

// ReadPrivateKey reads a private key file
func ReadPrivateKey(logger log.Logger, keyFile string) (privateKey ssh.Signer, err error) {

	// Read SSH Key
	keyBytes, err := ioutil.ReadFile(keyFile)
	if err != nil {
		logger.Warn("Private key could not be read", "error", string(err.Error()))
		return
	}

	// Get private key
	privateKey, err = ssh.ParsePrivateKey(keyBytes)
	if err != nil {
		logger.Warn("Private key could not be parsed", "error", err.Error())
	}
	return
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:17,代碼來源:keys.go

示例13: WrapHandlerForClustering

// WrapHandlerForClustering takes in Vault's HTTP handler and returns a setup
// function that returns both the original handler and one wrapped with cluster
// methods
func WrapHandlerForClustering(handler http.Handler, logger log.Logger) func() (http.Handler, http.Handler) {
	return func() (http.Handler, http.Handler) {
		// This mux handles cluster functions (right now, only forwarded requests)
		mux := http.NewServeMux()
		mux.HandleFunc("/cluster/local/forwarded-request", func(w http.ResponseWriter, req *http.Request) {
			freq, err := forwarding.ParseForwardedHTTPRequest(req)
			if err != nil {
				if logger != nil {
					logger.Error("http/forwarded-request-server: error parsing forwarded request", "error", err)
				}

				w.Header().Add("Content-Type", "application/json")

				// The response writer here is different from
				// the one set in Vault's HTTP handler.
				// Hence, set the Cache-Control explicitly.
				w.Header().Set("Cache-Control", "no-store")

				w.WriteHeader(http.StatusInternalServerError)

				type errorResponse struct {
					Errors []string
				}
				resp := &errorResponse{
					Errors: []string{
						err.Error(),
					},
				}

				enc := json.NewEncoder(w)
				enc.Encode(resp)
				return
			}

			// To avoid the risk of a forward loop in some pathological condition,
			// set the no-forward header
			freq.Header.Set(IntNoForwardingHeaderName, "true")
			handler.ServeHTTP(w, freq)
		})

		return handler, mux
	}
}
開發者ID:naunga,項目名稱:vault,代碼行數:46,代碼來源:cluster.go

示例14: acceptStreams

func acceptStreams(logger log.Logger, session *yamux.Session, streamCh chan net.Conn) grim.TaskFunc {
	return func(ctx context.Context) {
		defer close(streamCh)
		for {
			select {
			case <-ctx.Done():
				return
			default:
				stream, err := session.Accept()
				if err != nil {
					if err != io.EOF {
						logger.Error("multiplex conn accept failed", "err", err)
					}
					return
				}
				streamCh <- stream
			}
		}
	}
}
開發者ID:blacklabeldata,項目名稱:cerebrum,代碼行數:20,代碼來源:yamuxer.go

示例15: CreateCertificateRequest

// CreateCertificateRequest generates a new certificate request
func CreateCertificateRequest(logger log.Logger, key *rsa.PrivateKey, name, org, country, hostList string) (*x509.CertificateRequest, []byte, error) {

	// Create template
	logger.Info("Creating Certificate template")
	template := &x509.CertificateRequest{
		Subject: pkix.Name{
			Country:            []string{country},
			Organization:       []string{org},
			OrganizationalUnit: []string{name},
		},
	}

	// Associate hosts
	logger.Info("Adding Hosts to Certificate")
	hosts := strings.Split(hostList, ",")
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	// Create cert
	logger.Info("Generating Certificate")
	cert, err := x509.CreateCertificateRequest(rand.Reader, template, key)
	if err != nil {
		return nil, nil, err
	}

	return template, cert, nil
}
開發者ID:subsilent,項目名稱:kappa,代碼行數:33,代碼來源:keys.go


注:本文中的github.com/mgutz/logxi/v1.Logger類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。