1/*
2Copyright 2020 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package logs
18
19import (
20	"fmt"
21	"sort"
22
23	"github.com/go-logr/logr"
24	json "k8s.io/component-base/logs/json"
25)
26
27const (
28	jsonLogFormat = "json"
29)
30
31var logRegistry = NewLogFormatRegistry()
32
33// LogFormatRegistry store klog format registry
34type LogFormatRegistry struct {
35	registry map[string]logr.Logger
36	frozen   bool
37}
38
39// NewLogFormatRegistry return new init LogFormatRegistry struct
40func NewLogFormatRegistry() *LogFormatRegistry {
41	return &LogFormatRegistry{
42		registry: make(map[string]logr.Logger),
43		frozen:   false,
44	}
45}
46
47// Register new log format registry to global logRegistry
48func (lfr *LogFormatRegistry) Register(name string, logger logr.Logger) error {
49	if lfr.frozen {
50		return fmt.Errorf("log format is frozen, unable to register log format")
51	}
52	if _, ok := lfr.registry[name]; ok {
53		return fmt.Errorf("log format: %s already exists", name)
54	}
55	lfr.registry[name] = logger
56	return nil
57}
58
59// Get specified log format logger
60func (lfr *LogFormatRegistry) Get(name string) (logr.Logger, error) {
61	re, ok := lfr.registry[name]
62	if !ok {
63		return nil, fmt.Errorf("log format: %s does not exists", name)
64	}
65	return re, nil
66}
67
68// Set specified log format logger
69func (lfr *LogFormatRegistry) Set(name string, logger logr.Logger) error {
70	if lfr.frozen {
71		return fmt.Errorf("log format is frozen, unable to set log format")
72	}
73
74	lfr.registry[name] = logger
75	return nil
76}
77
78// Delete specified log format logger
79func (lfr *LogFormatRegistry) Delete(name string) error {
80	if lfr.frozen {
81		return fmt.Errorf("log format is frozen, unable to delete log format")
82	}
83
84	delete(lfr.registry, name)
85	return nil
86}
87
88// List names of registered log formats (sorted)
89func (lfr *LogFormatRegistry) List() []string {
90	formats := make([]string, 0, len(lfr.registry))
91	for f := range lfr.registry {
92		formats = append(formats, f)
93	}
94	sort.Strings(formats)
95	return formats
96}
97
98// Freeze freezes the log format registry
99func (lfr *LogFormatRegistry) Freeze() {
100	lfr.frozen = true
101}
102func init() {
103	// Text format is default klog format
104	logRegistry.Register(defaultLogFormat, nil)
105	logRegistry.Register(jsonLogFormat, json.JSONLogger)
106}
107