Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement internal logger #105

Merged
merged 5 commits into from
Apr 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Sources/SwiftQueue/JobBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ public final class JobBuilder {
return self
}

internal func build(job: Job) -> SqOperation {
return SqOperation(job: job, info: info)
internal func build(job: Job, logger: SwiftQueueLogger) -> SqOperation {
return SqOperation(job: job, info: info, logger: logger)
}

/// Add job to the JobQueue
Expand All @@ -107,6 +107,6 @@ public final class JobBuilder {
let queue = manager.getQueue(queueName: info.group)
let job = queue.createHandler(type: info.type, params: info.params)

queue.addOperation(build(job: job))
queue.addOperation(build(job: job, logger: manager.logger))
}
}
1 change: 0 additions & 1 deletion Sources/SwiftQueue/JobInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ struct JobInfo {

init?(dictionary: [String: Any]) {
guard let type = dictionary["type"] as? String else {
assertionFailure("Unable to retrieve Job type")
return nil
}

Expand Down
28 changes: 19 additions & 9 deletions Sources/SwiftQueue/SqOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ internal final class SqOperation: Operation {

var lastError: Swift.Error?

let logger: SwiftQueueLogger

override var name: String? { get { return info.uuid } set { } }

private var jobIsExecuting: Bool = false
Expand All @@ -36,9 +38,10 @@ internal final class SqOperation: Operation {
}
}

internal init(job: Job, info: JobInfo) {
internal init(job: Job, info: JobInfo, logger: SwiftQueueLogger) {
self.handler = job
self.info = info
self.logger = logger

self.constraints = [
DeadlineConstraint(),
Expand All @@ -56,6 +59,7 @@ internal final class SqOperation: Operation {

override func start() {
super.start()
logger.log(.verbose, jobId: info.uuid, message: "Job has been started by the system")
isExecuting = true
run()
}
Expand All @@ -65,19 +69,22 @@ internal final class SqOperation: Operation {
}

func cancel(with: Swift.Error) {
logger.log(.verbose, jobId: info.uuid, message: "Job has been canceled")
lastError = with
onTerminate()
super.cancel()
}

func onTerminate() {
logger.log(.verbose, jobId: info.uuid, message: "Job will not run anymore")
if isExecuting {
isFinished = true
}
}

// cancel before schedule and serialise
internal func abort(error: Swift.Error) {
logger.log(.verbose, jobId: info.uuid, message: "Job has not been scheduled due to \(error.localizedDescription)")
lastError = error
// Need to be called manually since the task is actually not in the queue. So cannot call cancel()
handler.onRemove(result: .fail(error))
Expand All @@ -94,6 +101,7 @@ internal final class SqOperation: Operation {
do {
try self.willRunJob()
} catch let error {
logger.log(.warning, jobId: info.uuid, message: "Job cannot run due to \(error.localizedDescription)")
// Will never run again
cancel(with: error)
return
Expand All @@ -102,14 +110,17 @@ internal final class SqOperation: Operation {
guard self.checkIfJobCanRunNow() else {
// Constraint fail.
// Constraint will call run when it's ready
logger.log(.verbose, jobId: info.uuid, message: "Job cannot run now. Execution is postponed")
return
}

logger.log(.verbose, jobId: info.uuid, message: "Job is running")
handler.onRun(callback: self)
}

internal func remove() {
let result = lastError.map(JobCompletion.fail) ?? JobCompletion.success
logger.log(.verbose, jobId: info.uuid, message: "Job is removed from the queue result=\(result)")
handler.onRemove(result: result)
}

Expand All @@ -129,6 +140,7 @@ extension SqOperation: JobResult {
}

private func completionFail(error: Swift.Error) {
logger.log(.warning, jobId: info.uuid, message: "Job completed with error \(error.localizedDescription)")
lastError = error

switch info.retries {
Expand Down Expand Up @@ -166,6 +178,7 @@ extension SqOperation: JobResult {
}

private func completionSuccess() {
logger.log(.verbose, jobId: info.uuid, message: "Job completed successfully")
lastError = nil
info.currentRepetition = 0

Expand Down Expand Up @@ -195,20 +208,17 @@ extension SqOperation: JobResult {

extension SqOperation {

convenience init?(dictionary: [String: Any], creator: JobCreator) {
convenience init?(json: String, creator: JobCreator, logger: SwiftQueueLogger) {
let dictionary = fromJSON(json) as? [String: Any] ?? [:]

guard let info = JobInfo(dictionary: dictionary) else {
assertionFailure("Unable to un-serialise job")
logger.log(.error, jobId: "UNKNOWN", message: "Unable to un-serialise job [\(json)]")
return nil
}

let job = creator.create(type: info.type, params: info.params)

self.init(job: job, info: info)
}

convenience init?(json: String, creator: JobCreator) {
let dict = fromJSON(json) as? [String: Any] ?? [:]
self.init(dictionary: dict, creator: creator)
self.init(job: job, info: info, logger: logger)
}

func toJSONString() -> String? {
Expand Down
7 changes: 5 additions & 2 deletions Sources/SwiftQueue/SqOperationQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ internal final class SqOperationQueue: OperationQueue {

private let queueName: String

init(_ queueName: String, _ creator: JobCreator, _ persister: JobPersister? = nil, _ isPaused: Bool = false) {
private let logger: SwiftQueueLogger

init(_ queueName: String, _ creator: JobCreator, _ persister: JobPersister? = nil, _ isPaused: Bool = false, logger: SwiftQueueLogger) {
self.creator = creator
self.persister = persister
self.queueName = queueName
self.logger = logger

super.init()

Expand All @@ -27,7 +30,7 @@ internal final class SqOperationQueue: OperationQueue {

private func loadSerializedTasks(name: String) {
persister?.restore(queueName: name).flatMapCompact { string -> SqOperation? in
SqOperation(json: string, creator: creator)
return SqOperation(json: string, creator: creator, logger: logger)
}.sorted {
$0.info.createTime < $1.info.createTime
}.forEach(addOperation)
Expand Down
76 changes: 76 additions & 0 deletions Sources/SwiftQueue/SwiftQueueLogger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//
// Created by Lucas Nelaupe on 18/4/18.
//

import Foundation

/// Specify different importance of logging
public enum LogLevel: Int {

/// Basic information about scheduling, running job and completion
case verbose = 1
/// Important but non fatal information
case warning = 2
/// Something went wrong during the scheduling or the execution
case error = 3

}

internal extension LogLevel {
var description: String {
switch self {
case .verbose:
return "verbose"
case .warning:
return "warning"
case .error:
return "error"
}
}
}

/// Func
public protocol SwiftQueueLogger {

/// Function called by the library to log an event
func log(_ level: LogLevel, jobId: @autoclosure () -> String, message: @autoclosure () -> String)

}

/// Class to compute the log and print to the console
open class ConsoleLogger: SwiftQueueLogger {

private let min: LogLevel

/// Define minimum level to log. By default, it will log everything
init(min: LogLevel = .verbose) {
self.min = min
}

/// Check for log level and create the output message
public final func log(_ level: LogLevel, jobId: @autoclosure () -> String, message: @autoclosure () -> String) {
if min.rawValue <= level.rawValue {
printComputed(output: "[SwiftQueue] level=\(level.description) jobId=\(jobId()) message=\(message())")
}
}

/// Print with default `print()` function. Can be override to changed the output
open func printComputed(output: String) {
print(output)
}

}

/// Class to ignore all kind of logs
public class NoLogger: SwiftQueueLogger {

/// Singleton instance to avoid multiple instance across all queues
public static let shared = NoLogger()

private init() {}

/// Default implementation that will not log anything
public func log(_ level: LogLevel, jobId: @autoclosure () -> String, message: @autoclosure () -> String) {
// Nothing to do
}
}
11 changes: 7 additions & 4 deletions Sources/SwiftQueue/SwiftQueueManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Foundation

/// Global manager to perform operations on all your queues/
/// You will have to keep this instance. We highly recommend you to store this instance in a Singleton
/// Creating and instance of this class will automatically un-serialise your jobs and schedule them
/// Creating and instance of this class will automatically un-serialise your jobs and schedule them
public final class SwiftQueueManager {

private let creator: JobCreator
Expand All @@ -17,14 +17,17 @@ public final class SwiftQueueManager {

private var isPaused = true

internal let logger: SwiftQueueLogger

/// Create a new QueueManager with creators to instantiate Job
public init(creator: JobCreator, persister: JobPersister? = nil) {
public init(creator: JobCreator, persister: JobPersister? = nil, logger: SwiftQueueLogger = NoLogger.shared) {
self.creator = creator
self.persister = persister
self.logger = logger

if let data = persister {
for queueName in data.restore() {
manage[queueName] = SqOperationQueue(queueName, creator, persister, isPaused)
manage[queueName] = SqOperationQueue(queueName, creator, persister, isPaused, logger: logger)
}
}
start()
Expand All @@ -51,7 +54,7 @@ public final class SwiftQueueManager {
}

private func createQueue(queueName: String) -> SqOperationQueue {
let queue = SqOperationQueue(queueName, creator, persister, isPaused)
let queue = SqOperationQueue(queueName, creator, persister, isPaused, logger: logger)
manage[queueName] = queue
return queue
}
Expand Down
14 changes: 14 additions & 0 deletions SwiftQueue.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@
1E68ED598FA15EF36B431571 /* Constrains+Deadline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E68EF96F1DE038FFF94FCD8 /* Constrains+Deadline.swift */; };
1E68EDC2230D2FACC61E7868 /* Constrains+Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E68E940C8373221E3EDC771 /* Constrains+Delay.swift */; };
1E68EE914B5B51CDB2BD7C4D /* Constraints+UniqueUUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E68E002DC39E9BBE4A0A06A /* Constraints+UniqueUUID.swift */; };
95A210264F99EAC94629D786 /* SwiftQueueLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */; };
95A214C332FB7115C12F88D2 /* LoggerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95A2193AF039008357A8D362 /* LoggerTests.swift */; };
95A21576964E9A1FE1EDC5DB /* SwiftQueueLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */; };
95A21B708B2910C7CF8BD39D /* SwiftQueueLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */; };
95A21FA05AABFA4A59096E8E /* SwiftQueueLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */; };
B06405031FA04AA000086C69 /* UserDefaultsPersister.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D8479A11F82A84A00B3BBFB /* UserDefaultsPersister.swift */; };
B06405041FA04AA000086C69 /* SwiftQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D8479A21F82A84A00B3BBFB /* SwiftQueue.swift */; };
B06405061FA04AA000086C69 /* Constraints.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D8479A61F82A84B00B3BBFB /* Constraints.swift */; };
Expand Down Expand Up @@ -96,6 +101,8 @@
1E68E82C1E071C7AA1AC4BB6 /* Constrains+Network.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Constrains+Network.swift"; path = "SwiftQueue/Constrains+Network.swift"; sourceTree = "<group>"; };
1E68E940C8373221E3EDC771 /* Constrains+Delay.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Constrains+Delay.swift"; path = "SwiftQueue/Constrains+Delay.swift"; sourceTree = "<group>"; };
1E68EF96F1DE038FFF94FCD8 /* Constrains+Deadline.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Constrains+Deadline.swift"; path = "SwiftQueue/Constrains+Deadline.swift"; sourceTree = "<group>"; };
95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftQueueLogger.swift; path = SwiftQueue/SwiftQueueLogger.swift; sourceTree = "<group>"; };
95A2193AF039008357A8D362 /* LoggerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoggerTests.swift; sourceTree = "<group>"; };
B064050E1FA04AA000086C69 /* SwiftQueue.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftQueue.framework; sourceTree = BUILT_PRODUCTS_DIR; };
B064051D1FA04AAC00086C69 /* SwiftQueue.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftQueue.framework; sourceTree = BUILT_PRODUCTS_DIR; };
B064052C1FA04CCF00086C69 /* SwiftQueue.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftQueue.framework; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -174,6 +181,7 @@
D0B7C62E5894FA6EE00D3160 /* PersisterTests.swift */,
D0B7C898344F1EB3A0815D67 /* ConstraintDeadlineTests.swift */,
D0B7C2A57EFC83B94E3146B3 /* Package.swift */,
95A2193AF039008357A8D362 /* LoggerTests.swift */,
);
name = SwiftQueueTests;
path = Tests/SwiftQueueTests;
Expand Down Expand Up @@ -217,6 +225,7 @@
D0B7C4E41A1BF73329A7D03D /* JobInfo.swift */,
D0B7CB3B79E039D3B11D8921 /* JobBuilder.swift */,
D0B7CB571CECEEA34DD07398 /* SqOperationQueue.swift */,
95A217FDB8197696002CE25C /* SwiftQueueLogger.swift */,
);
path = Sources;
sourceTree = SOURCE_ROOT;
Expand Down Expand Up @@ -360,6 +369,7 @@
D0B7CC03343274087B4C7955 /* JobInfo.swift in Sources */,
D0B7C8729FA2F6EF3A6C42F8 /* JobBuilder.swift in Sources */,
D0B7C9AE1E4717DE474FD804 /* SqOperationQueue.swift in Sources */,
95A21FA05AABFA4A59096E8E /* SwiftQueueLogger.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -380,6 +390,7 @@
D0B7C0848D0FF83C8B04EBB6 /* JobInfo.swift in Sources */,
D0B7CFA2089DFF576E0D765B /* JobBuilder.swift in Sources */,
D0B7C2F3F465996A939596F7 /* SqOperationQueue.swift in Sources */,
95A21576964E9A1FE1EDC5DB /* SwiftQueueLogger.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -400,6 +411,7 @@
D0B7CC89D901F6C8AD2666D9 /* JobInfo.swift in Sources */,
D0B7C6B8833437575C438715 /* JobBuilder.swift in Sources */,
D0B7C276BFD64AF0EA757C55 /* SqOperationQueue.swift in Sources */,
95A21B708B2910C7CF8BD39D /* SwiftQueueLogger.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -420,6 +432,7 @@
D0B7C996BDB2A748B6B8843A /* JobInfo.swift in Sources */,
D0B7C437539F0BEE35FBE8F0 /* JobBuilder.swift in Sources */,
D0B7CD1E797A69C89CB0ADE2 /* SqOperationQueue.swift in Sources */,
95A210264F99EAC94629D786 /* SwiftQueueLogger.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -436,6 +449,7 @@
D0B7C50629CD1E0F8F40E7F3 /* ConstraintNetworkTests.swift in Sources */,
D0B7C9B78BFACD1BEDA4D42E /* PersisterTests.swift in Sources */,
D0B7C6C3E08DF6BFD0737E4D /* ConstraintDeadlineTests.swift in Sources */,
95A214C332FB7115C12F88D2 /* LoggerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
Loading