fix
杨锴
2025-06-16 3fa53409f5132333ce6d83fff796e108ddd62090
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//
//  FileDestination.swift
//  XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
//  Created by Dave Wood on 2014-06-06.
//  Copyright © 2014 Dave Wood, Cerebral Gardens.
//  Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
 
import Foundation
import Dispatch
 
// MARK: - FileDestination
/// A standard destination that outputs log details to a file
open class FileDestination: BaseQueuedDestination {
    // MARK: - Properties
    /// Logger that owns the destination object
    open override var owner: XCGLogger? {
        didSet {
            if owner != nil {
                openFile()
            }
            else {
                closeFile()
            }
        }
    }
 
    /// FileURL of the file to log to
    open var writeToFileURL: URL? = nil {
        didSet {
            openFile()
        }
    }
 
    /// File handle for the log file
    internal var logFileHandle: FileHandle? = nil
 
    /// Option: whether or not to append to the log file if it already exists
    internal var shouldAppend: Bool
 
    /// Option: if appending to the log file, the string to output at the start to mark where the append took place
    internal var appendMarker: String?
 
    /// Option: Attributes to use when creating a new file
    internal var fileAttributes: [FileAttributeKey: Any]? = nil
 
    // MARK: - Life Cycle
    public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [FileAttributeKey: Any]? = nil) {
        self.shouldAppend = shouldAppend
        self.appendMarker = appendMarker
        self.fileAttributes = attributes
 
        if writeToFile is NSString {
            writeToFileURL = URL(fileURLWithPath: writeToFile as! String)
        }
        else if let writeToFile = writeToFile as? URL, writeToFile.isFileURL {
            writeToFileURL = writeToFile
        }
        else {
            writeToFileURL = nil
        }
 
        super.init(owner: owner, identifier: identifier)
 
        if owner != nil {
            openFile()
        }
    }
 
    deinit {
        // close file stream if open
        closeFile()
    }
 
    // MARK: - File Handling Methods
    /// Open the log file for writing.
    ///
    /// - Parameters:   None
    ///
    /// - Returns:  Nothing
    ///
    private func openFile() {
        guard let owner = owner else { return }
 
        if logFileHandle != nil {
            closeFile()
        }
 
        guard let writeToFileURL = writeToFileURL else { return }
 
        let fileManager: FileManager = FileManager.default
        let fileExists: Bool = fileManager.fileExists(atPath: writeToFileURL.path)
        if !shouldAppend || !fileExists {
            fileManager.createFile(atPath: writeToFileURL.path, contents: nil, attributes: fileAttributes)
        }
 
        do {
            logFileHandle = try FileHandle(forWritingTo: writeToFileURL)
            if fileExists && shouldAppend {
                logFileHandle?.seekToEndOfFile()
 
                if let appendMarker = appendMarker,
                    let encodedData = "\(appendMarker)\n".data(using: String.Encoding.utf8) {
 
                    _try({
                        self.logFileHandle?.write(encodedData)
                    },
                    catch: { (exception: NSException) in
                        print("Objective-C Exception occurred: \(exception)")
                    })
                }
            }
        }
        catch let error as NSError {
            owner._logln("Attempt to open log file for \(fileExists && shouldAppend ? "appending" : "writing") failed: \(error.localizedDescription)", level: .error, source: self)
            logFileHandle = nil
            return
        }
 
        owner.logAppDetails(selectedDestination: self)
 
        let logDetails = LogDetails(level: .info, date: Date(), message: "XCGLogger " + (fileExists && shouldAppend ? "appending" : "writing") + " log to: " + writeToFileURL.absoluteString, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)
        owner._logln(logDetails.message, level: logDetails.level, source: self)
        if owner.destination(withIdentifier: identifier) == nil {
            processInternal(logDetails: logDetails)
        }
    }
 
    /// Close the log file.
    ///
    /// - Parameters:   None
    ///
    /// - Returns:  Nothing
    ///
    private func closeFile() {
        logFileHandle?.synchronizeFile()
        logFileHandle?.closeFile()
        logFileHandle = nil
    }
 
    /// Force any buffered data to be written to the file.
    ///
    /// - Parameters:
    ///     - closure:  An optional closure to execute after the file has been rotated.
    ///
    /// - Returns:      Nothing.
    ///
    open func flush(closure: (() -> Void)? = nil) {
        if let logQueue = logQueue {
            logQueue.async {
                self.logFileHandle?.synchronizeFile()
                closure?()
            }
        }
        else {
            logFileHandle?.synchronizeFile()
            closure?()
        }
    }
 
    /// Rotate the log file, storing the existing log file in the specified location.
    ///
    /// - Parameters:
    ///     - archiveToFile:    FileURL or path (as String) to where the existing log file should be rotated to.
    ///     - closure:          An optional closure to execute after the file has been rotated.
    ///
    /// - Returns:
    ///     - true:     Log file rotated successfully.
    ///     - false:    Error rotating the log file.
    ///
    @discardableResult open func rotateFile(to archiveToFile: Any, closure: ((_ success: Bool) -> Void)? = nil) -> Bool {
        var archiveToFileURL: URL? = nil
 
        if archiveToFile is NSString {
            archiveToFileURL = URL(fileURLWithPath: archiveToFile as! String)
        }
        else if let archiveToFile = archiveToFile as? URL, archiveToFile.isFileURL {
            archiveToFileURL = archiveToFile
        }
        else {
            closure?(false)
            return false
        }
 
        if let archiveToFileURL = archiveToFileURL,
          let writeToFileURL = writeToFileURL {
 
            let fileManager: FileManager = FileManager.default
            guard !fileManager.fileExists(atPath: archiveToFileURL.path) else { closure?(false); return false }
 
            closeFile()
            haveLoggedAppDetails = false
 
            do {
                try fileManager.moveItem(atPath: writeToFileURL.path, toPath: archiveToFileURL.path)
            }
            catch let error as NSError {
                openFile()
                owner?._logln("Unable to rotate file \(writeToFileURL.path) to \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self)
                closure?(false)
                return false
            }
 
            do {
                if let identifierData: Data = identifier.data(using: .utf8) {
                    try archiveToFileURL.setExtendedAttribute(data: identifierData, forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey)
                }
                if let timestampData: Data = "\(Date().timeIntervalSince1970)".data(using: .utf8) {
                    try archiveToFileURL.setExtendedAttribute(data: timestampData, forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey)
                }
            }
            catch let error as NSError {
                owner?._logln("Unable to set extended file attributes on file \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self)
            }
 
            owner?._logln("Rotated file \(writeToFileURL.path) to \(archiveToFileURL.path)", level: .info, source: self)
            openFile()
            closure?(true)
            return true
        }
 
        closure?(false)
        return false
    }
 
    // MARK: - Overridden Methods
    /// Write the log to the log file.
    ///
    /// - Parameters:
    ///     - message:   Formatted/processed message ready for output.
    ///
    /// - Returns:  Nothing
    ///
    open override func write(message: String) {
        if let encodedData = "\(message)\n".data(using: String.Encoding.utf8) {
            _try({
                self.logFileHandle?.write(encodedData)
            },
            catch: { (exception: NSException) in
                print("Objective-C Exception occurred: \(exception)")
            })
        }
    }
}