|
| 1 | +/* |
| 2 | +Copyright 2023 The Kruise Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package util |
| 18 | + |
| 19 | +import ( |
| 20 | + "encoding/json" |
| 21 | + "flag" |
| 22 | + "fmt" |
| 23 | + "log" |
| 24 | + "os" |
| 25 | + "path/filepath" |
| 26 | +) |
| 27 | + |
| 28 | +var ( |
| 29 | + protectionLogger *log.Logger |
| 30 | + protectionLogPath string |
| 31 | +) |
| 32 | + |
| 33 | +const ( |
| 34 | + ProtectionEventPub = "PodUnavailableBudget" |
| 35 | + ProtectionEventDeletionProtection = "DeletionProtection" |
| 36 | +) |
| 37 | + |
| 38 | +type ProtectionLoggerInfo struct { |
| 39 | + // PUB, ProtectionDeletion |
| 40 | + Event string |
| 41 | + Kind string |
| 42 | + Namespace string |
| 43 | + Name string |
| 44 | + UserAgent string |
| 45 | +} |
| 46 | + |
| 47 | +func init() { |
| 48 | + flag.StringVar(&protectionLogPath, "protection-log-path", "/log", "protection log path, for example pub, delete_protection") |
| 49 | +} |
| 50 | +func InitProtectionLogger() error { |
| 51 | + err := os.MkdirAll(protectionLogPath, 0644) |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("MkdirAll(%s) failed: %s", protectionLogPath, err.Error()) |
| 54 | + } |
| 55 | + file, err := os.OpenFile(filepath.Join(protectionLogPath, "protection.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) |
| 56 | + if err != nil { |
| 57 | + return fmt.Errorf("openFile(%s) failed: %s", filepath.Join(protectionLogPath, "protection.log"), err.Error()) |
| 58 | + } |
| 59 | + protectionLogger = log.New(file, "", 0) |
| 60 | + return nil |
| 61 | +} |
| 62 | + |
| 63 | +func LoggerProtectionInfo(event, kind, ns, name, userAgent string) { |
| 64 | + // compatible with go test |
| 65 | + if protectionLogger == nil { |
| 66 | + return |
| 67 | + } |
| 68 | + info := ProtectionLoggerInfo{ |
| 69 | + Event: event, |
| 70 | + Kind: kind, |
| 71 | + Namespace: ns, |
| 72 | + Name: name, |
| 73 | + UserAgent: userAgent, |
| 74 | + } |
| 75 | + by, _ := json.Marshal(info) |
| 76 | + protectionLogger.Println(string(by)) |
| 77 | +} |
0 commit comments