Skip to content

Commit b0e6a60

Browse files
committed
use defer based approach
1 parent 9f2ca6f commit b0e6a60

File tree

3 files changed

+25
-12
lines changed

3 files changed

+25
-12
lines changed

acquisition/acquisition.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ type Acquisition struct {
3434
TmpDir string `json:"tmp_dir"`
3535
SdCard string `json:"sdcard"`
3636
Cpu string `json:"cpu"`
37+
closeLog func() `json:"-"`
3738
}
3839

3940
// New returns a new Acquisition instance.
@@ -77,16 +78,24 @@ func New(path string) (*Acquisition, error) {
7778

7879
// Init logging file
7980
logPath := filepath.Join(acq.StoragePath, "command.log")
80-
log.EnableFileLog(log.DEBUG, logPath)
81+
closeLog, err := log.EnableFileLog(log.DEBUG, logPath)
82+
if err != nil {
83+
return nil, fmt.Errorf("failed to enable file logging: %v", err)
84+
}
85+
86+
// Store cleanup function for later use
87+
acq.closeLog = closeLog
8188

8289
return &acq, nil
8390
}
8491

8592
func (a *Acquisition) Complete() {
8693
a.Completed = time.Now().UTC()
8794

88-
// Close the log file before cleanup
89-
log.CloseFileLog()
95+
// Ensure log file is closed before cleanup operations
96+
if a.closeLog != nil {
97+
defer a.closeLog()
98+
}
9099

91100
if a.Collector != nil {
92101
a.Collector.Clean()

acquisition/secure.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,10 @@ func (a *Acquisition) StoreSecurely() error {
8888
return fmt.Errorf("failed to delete the unencrypted compressed archive: %v", err)
8989
}
9090

91-
// Close the log file before removing the acquisition directory
92-
log.CloseFileLog()
91+
// Ensure log file is closed before removing the acquisition directory
92+
if a.closeLog != nil {
93+
defer a.closeLog()
94+
}
9395

9496
err = os.RemoveAll(a.StoragePath)
9597
if err != nil {

log/logger.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,24 +129,26 @@ func Coloring(enable bool) {
129129
log.Color = enable
130130
}
131131

132-
func EnableFileLog(level LEVEL, filePath string) error {
132+
func EnableFileLog(level LEVEL, filePath string) (func(), error) {
133133
if filePath == "" {
134-
return errors.New("invalid file path")
134+
return nil, errors.New("invalid file path")
135135
}
136136

137137
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
138138
if err != nil {
139-
return err
139+
return nil, err
140140
}
141141
log.fd = file
142142
log.fileName = filePath
143-
return nil
143+
144+
// Return cleanup function for defer pattern
145+
cleanup := func() {
146+
CloseFileLog()
147+
}
148+
return cleanup, nil
144149
}
145150

146151
func CloseFileLog() {
147-
log.fd.Close()
148-
log.fd = nil
149-
log.fileName = ""
150152
if log.fd != nil {
151153
log.fd.Close()
152154
log.fd = nil

0 commit comments

Comments
 (0)