GithubHelp home page GithubHelp logo

nike-inc / willow Goto Github PK

View Code? Open in Web Editor NEW
1.3K 40.0 80.0 522 KB

Willow is a powerful, yet lightweight logging library written in Swift.

License: MIT License

Swift 96.27% Ruby 0.67% C 3.06%

willow's Introduction

Willow

Build Status CocoaPods Compatible Carthage Compatible Platform

Willow is a powerful, yet lightweight logging library written in Swift.

Features

  • Default Log Levels
  • Custom Log Levels
  • Simple Logging Functions using Closures
  • Configurable Synchronous or Asynchronous Execution
  • Thread-Safe Logging Output (No Log Mangling)
  • Custom Writers through Dependency Injection
  • Custom Modifiers through Dependency Injection per Writer
  • Supports Multiple Simultaneous Writers
  • Shared Loggers Between Frameworks
  • Shared Locks or Queues Between Multiple Loggers
  • Comprehensive Unit Test Coverage
  • Complete Documentation

Requirements

  • iOS 9.0+ / Mac OS X 10.11+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 9.3+
  • Swift 4.1+

Migration Guides

Communication

  • Need help? Open an issue.
  • Have a feature request? Open an issue.
  • Find a bug? Open an issue.
  • Want to contribute? Fork the repo and submit a pull request.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

[sudo] gem install cocoapods

CocoaPods 1.3+ is required.

To integrate Willow into your project, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.0'
use_frameworks!

pod 'Willow', '~> 5.0'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Willow into your Xcode project using Carthage, specify it in your Cartfile:

github "Nike-Inc/Willow" ~> 5.0

Run carthage update to build the framework and drag the built Willow.framework into your Xcode project.

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Willow does support its use on supported platforms.

Once you have your Swift package set up, adding Willow as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/Nike-Inc/Willow.git", majorVersion: 5)
]

Usage

Creating a Logger

import Willow

let defaultLogger = Logger(logLevels: [.all], writers: [ConsoleWriter()])

The Logger initializer takes three parameters to customize the behavior of the logger instance.

  • logLevels: [LogLevel] - The log message levels that should be processed. Messages that don't match the current log level are not processed.

  • writers: [LogWriter] - The array of writers to write to. Writers can be used to log output to a specific destination such as the console, a file, or an external service.

  • executionMethod: ExecutionMethod = .synchronous(lock: NSRecursiveLock()) - The execution method used when writing messages.

Logger objects can only be customized during initialization. If you need to change a Logger at runtime, it is advised to create an additional logger with a custom configuration to fit your needs. It is perfectly acceptable to have many different Logger instances running simultaneously.

Thread Safety

The print function does not guarantee that the String parameter will be fully logged to the console. If two print calls are happening simultaneously from two different queues (threads), the messages can get mangled, or intertwined. Willow guarantees that messages are completely finished writing before starting on the next one.

It is important to note that by creating multiple Logger instances, you can potentially lose the guarantee of thread-safe logging. If you want to use multiple Logger instances, you should create a NSRecursiveLock or DispatchQueue that is shared between both configurations. For more info, see the Advanced Usage section.

Logging Messages and String Messages

Willow can log two different types of objects: Messages and Strings.

Log Messages

Messages are structured data with a name and a dictionary of attributes. Willow declares the LogMessage protocol which frameworks and applications can use as the basis for concrete implementations. Messages are a good choice if you want to provide context information along with the log text (e.g. routing log information to an external system like New Relic).

enum Message: LogMessage {
    case requestStarted(url: URL)
    case requestCompleted(url: URL, response: HTTPURLResponse)

    var name: String {
        switch self {
        case .requestStarted:   return "Request started"
        case .requestCompleted: return "Request completed"
        }
    }

    var attributes: [String: Any] {
        switch self {
        case let .requestStarted(url):
            return ["url": url]

        case let .requestCompleted(url, response):
            return ["url": url, "response_code": response.statusCode]
        }
    }
}

let url = URL(string: "https://httpbin.org/get")!

log.debug(Message.requestStarted(url: url))
log.info(Message.requestStarted(url: url))
log.event(Message.requestStarted(url: url))
log.warn(Message.requestStarted(url: url))
log.error(Message.requestStarted(url: url))

Log Message Strings

Log message strings are just String instances with no additional data.

let url = URL(string: "https://httpbin.org/get")!

log.debugMessage("Request Started: \(url)")
log.infoMessage("Request Started: \(url)")
log.eventMessage("Request Started: \(url)")
log.warnMessage("Request Started: \(url)")
log.errorMessage("Request Started: \(url)")

The log message string APIs have the Message suffix on the end to avoid ambiguity with the log message APIs. The multi-line escaping closure APIs collide without the suffix.

Logging Messages with Closures

The logging syntax of Willow was optimized to make logging as lightweight and easy to remember as possible. Developers should be able to focus on the task at hand and not remembering how to write a log message.

Single Line Closures

let log = Logger()

// Option 1
log.debugMessage("Debug Message")    // Debug Message
log.infoMessage("Info Message")      // Info Message
log.eventMessage("Event Message")    // Event Message
log.warnMessage("Warn Message")      // Warn Message
log.errorMessage("Error Message")    // Error Message

// or

// Option 2
log.debugMessage { "Debug Message" } // Debug Message
log.infoMessage { "Info Message" }   // Info Message
log.eventMessage { "Event Message" } // Event Message
log.warnMessage { "Warn Message" }   // Warn Message
log.errorMessage { "Error Message" } // Error Message

Both of these approaches are equivalent. The first set of APIs accept autoclosures and the second set accept closures.

Feel free to use whichever syntax you prefer for your project. Also, by default, only the String returned by the closure will be logged. See the Log Modifiers section for more information about customizing log message formats.

The reason both sets of APIs use closures to extract the log message is performance.

There are some VERY important performance considerations when designing a logging solution that are described in more detail in the Closure Performance section.

Multi-Line Closures

Logging a message is easy, but knowing when to add the logic necessary to build a log message and tune it for performance can be a bit tricky. We want to make sure logic is encapsulated and very performant. Willow log level closures allow you to cleanly wrap all the logic to build up the message.

log.debugMessage {
    // First let's run a giant for loop to collect some info
    // Now let's scan through the results to get some aggregate values
    // Now I need to format the data
    return "Computed Data Value: \(dataValue)"
}

log.infoMessage {
    let countriesString = ",".join(countriesArray)
    return "Countries: \(countriesString)"
}

Unlike the Single Line Closures, the Multi-Line Closures require a return declaration.

Closure Performance

Willow works exclusively with logging closures to ensure the maximum performance in all situations. Closures defer the execution of all the logic inside the closure until absolutely necessary, including the string evaluation itself. In cases where the Logger instance is disabled, log execution time was reduced by 97% over the traditional log message methods taking a String parameter. Additionally, the overhead for creating a closure was measured at 1% over the traditional method making it negligible. In summary, closures allow Willow to be extremely performant in all situations.

Disabling a Logger

The Logger class has an enabled property to allow you to completely disable logging. This can be helpful for turning off specific Logger objects at the app level, or more commonly to disable logging in a third-party library.

let log = Logger()
log.enabled = false

// No log messages will get sent to the registered Writers

log.enabled = true

// We're back in business...

Synchronous and Asynchronous Logging

Logging can greatly affect the runtime performance of your application or library. Willow makes it very easy to log messages synchronously or asynchronously. You can define this behavior when creating the LoggerConfiguration for your Logger instance.

let queue = DispatchQueue(label: "serial.queue", qos: .utility)
let log = Logger(logLevels: [.all], writers: [ConsoleWriter()], executionMethod: .asynchronous(queue: queue))

Synchronous Logging

Synchronous logging is very helpful when you are developing your application or library. The log operation will be completed before executing the next line of code. This can be very useful when stepping through the debugger. The downside is that this can seriously affect performance if logging on the main thread.

Asynchronous Logging

Asynchronous logging should be used for deployment builds of your application or library. This will offload the logging operations to a separate dispatch queue that will not affect the performance of the main thread. This allows you to still capture logs in the manner that the Logger is configured, yet not affect the performance of the main thread operations.

These are large generalizations about the typical use cases for one approach versus the other. Before making a final decision about which approach to use when, you should really break down your use case in detail.

Log Writers

Writing log messages to various locations is an essential feature of any robust logging library. This is made possible in Willow through the LogWriter protocol.

public protocol LogWriter {
    func writeMessage(_ message: String, logLevel: LogLevel)
    func writeMessage(_ message: Message, logLevel: LogLevel)
}

Again, this is an extremely lightweight design to allow for ultimate flexibility. As long as your LogWriter classes conform, you can do anything with those log messages that you want. You could write the message to the console, append it to a file, send it to a server, etc. Here's a quick look at a simple write that writes to the console.

open class ConsoleWriter: LogMessageWriter {
    open func writeMessage(_ message: String, logLevel: LogLevel) {
        print(message)
    }

    open func writeMessage(_ message: LogMessage, logLevel: LogLevel) {
        let message = "\(message.name): \(message.attributes)"
        print(message)
    }
}

Log Modifiers

Log message customization is something that Willow specializes in. Some devs want to add a prefix to their library output, some want different timestamp formats, some even want emoji! There's no way to predict all the types of custom formatting teams are going to want to use. This is where LogModifier objects come in.

public protocol LogModifier {
    func modifyMessage(_ message: String, with logLevel: LogLevel) -> String
}

The LogModifier protocol has only a single API. It receives the message and logLevel and returns a newly formatted String. This is about as flexible as you can get.

As an added layer of convenience, writers intending to output strings (e.g. writing to the console, files, etc.) can conform to the LogModifierWritier protocol. The LogModifierWriter protocol adds an array of LogModifier objects to the LogWriter that can be applied to the message before it is output using the modifyMessage(_:logLevel) API in the extension.

Let's walk through a simple example for adding a prefix to a logger for the debug and info log levels.

class PrefixModifier: LogModifier {
    func modifyMessage(_ message: String, with logLevel: Logger.LogLevel) -> String {
        return "[Willow] \(message)"
    }
}

let prefixModifiers = [PrefixModifier()]
let writers = [ConsoleWriter(modifiers: prefixModifiers)]
let log = Logger(logLevels: [.debug, .info], writers: writers)

To apply modifiers consistently to strings, LogModifierWriter objects should call modifyMessage(_:logLevel) to create a new string based on the original string with all the modifiers applied in order.

open func writeMessage(_ message: String, logLevel: LogLevel) {
    let message = modifyMessage(message, logLevel: logLevel)
    print(message)
}

Multiple Modifiers

Multiple LogModifier objects can be stacked together onto a single log level to perform multiple actions. Let's walk through using the TimestampModifier (prefixes the message with a timestamp) in combination with an EmojiModifier.

class EmojiModifier: LogModifier {
    func modifyMessage(_ message: String, with logLevel: LogLevel) -> String {
        return "๐Ÿš€๐Ÿš€๐Ÿš€ \(message)"
    }
}

let writers: = [ConsoleWriter(modifiers: [EmojiModifier(), TimestampModifier()])]
let log = Logger(logLevels: [.all], writers: writers)

Willow doesn't have any hard limits on the total number of LogModifier objects that can be applied to a single log level. Just keep in mind that performance is key.

The default ConsoleWriter will execute the modifiers in the same order they were added into the Array. In the previous example, Willow would log a much different message if the TimestampModifier was inserted before the EmojiModifier.

OSLog

The OSLogWriter class allows you to use the os_log APIs within the Willow system. In order to use it, all you need to do is to create the LogModifier instance and add it to the Logger.

let writers = [OSLogWriter(subsystem: "com.nike.willow.example", category: "testing")]
let log = Logger(logLevels: [.all], writers: writers)

log.debugMessage("Hello world...coming to your from the os_log APIs!")

Multiple Writers

So what about logging to both a file and the console at the same time? No problem. You can pass multiple LogWriter objects into the Logger initializer. The Logger will execute each LogWriter in the order it was passed in. For example, let's create a FileWriter and combine that with our ConsoleWriter.

public class FileWriter: LogWriter {
    public func writeMessage(_ message: String, logLevel: Logger.LogLevel, modifiers: [LogMessageModifier]?) {
	    var message = message
        modifiers?.map { message = $0.modifyMessage(message, with: logLevel) }
        // Write the formatted message to a file (We'll leave this to you!)
    }

    public func writeMessage(_ message: LogMessage, logLevel: LogLevel) {
        let message = "\(message.name): \(message.attributes)"
        // Write the formatted message to a file (We'll leave this to you!)
    }
}

let writers: [LogMessageWriter] = [FileWriter(), ConsoleWriter()]
let log = Logger(logLevels: [.all], writers: writers)

LogWriter objects can also be selective about which modifiers they want to run for a particular log level. All the examples run all the modifiers, but you can be selective if you want to be.


Advanced Usage

Creating Custom Log Levels

Depending upon the situation, the need to support additional log levels may arise. Willow can easily support additional log levels through the art of bitmasking. Since the internal RawValue of a LogLevel is a UInt, Willow can support up to 32 log levels simultaneously for a single Logger. Since there are 7 default log levels, Willow can support up to 27 custom log levels for a single logger. That should be more than enough to handle even the most complex of logging solutions.

Creating custom log levels is very simple. Here's a quick example of how to do so. First, you must create a LogLevel extension and add your custom values.

extension LogLevel {
    private static var verbose = LogLevel(rawValue: 0b00000000_00000000_00000001_00000000)
}

It's a good idea to make the values for custom log levels var instead of let. In the event of two frameworks using the same custom log level bit mask, the application can re-assign one of the frameworks to a new value.

Now that we have a custom log level called verbose, we need to extend the Logger class to be able to easily call it.

extension Logger {
    public func verboseMessage(_ message: @autoclosure @escaping () -> String) {
    	logMessage(message, with: .verbose)
    }

    public func verboseMessage(_ message: @escaping () -> String) {
    	logMessage(message, with: .verbose)
    }
}

Finally, using the new log level is a simple as...

let log = Logger(logLevels: [.all], writers: [ConsoleWriter()])
log.verboseMessage("My first verbose log message!")

The all log level contains a bitmask where all bits are set to 1. This means that the all log level will contain all custom log levels automatically.

Shared Loggers between Frameworks

Defining a single Logger and sharing that instance several frameworks can be very advantageous, especially with the addition of Frameworks in iOS 8. Now that we're going to be creating more frameworks inside our own apps to be shared between apps, extensions and third party libraries, wouldn't it be nice if we could share Logger instances?

Let's walk through a quick example of a Math framework sharing a Logger with it's parent Calculator app.

//=========== Inside Math.swift ===========
public var log: Logger?

//=========== Calculator.swift ===========
import Math

let writers: [LogMessageWriter] = [FileWriter(), ConsoleWriter()]
var log = Logger(logLevels: [.all], writers: writers)

// Set the Math.log instance to the Calculator.log to share the same Logger instance
Math.log = log

It's very simple to swap out a pre-existing Logger with a new one.

Multiple Loggers, One Queue

The previous example showed how to share Logger instances between multiple frameworks. Something more likely though is that you would want to have each third party library or internal framework to have their own Logger with their own configuration. The one thing that you really want to share is the NSRecursiveLock or DispatchQueue that they run on. This will ensure all your logging is thread-safe. Here's the previous example demonstrating how to create multiple Logger instances and still share the queue.

//=========== Inside Math.swift ===========
public var log: Logger?

//=========== Calculator.swift ===========
import Math

// Create a single queue to share
let sharedQueue = DispatchQueue(label: "com.math.logger", qos: .utility)

// Create the Calculator.log with multiple writers and a .Debug log level
let writers: [LogMessageWriter] = [FileWriter(), ConsoleWriter()]

var log = Logger(
    logLevels: [.all],
    writers: writers,
    executionMethod: .asynchronous(queue: sharedQueue)
)

// Replace the Math.log with a new instance with all the same configuration values except a shared queue
Math.log = Logger(
    logLevels: log.logLevels,
    writers: [ConsoleWriter()],
    executionMethod: .asynchronous(queue: sharedQueue)
)

Willow is a very lightweight library, but its flexibility allows it to become very powerful if you so wish.


Adding Message Filters

Sometimes you may wish to have finer-grained control over when some log messages are included. For instance, if you wanted to ignore logs that have a given attribute, based on whatever dynamic logic you have.

This is useful if you have a way to toggle log subsystems on/off within the app in a DEBUG/ADHOC scenario.

To define a filter, create a type that implements the LogFilter protocol.

Here is an example of a filter that can conditionally exclude noisy logs for an analytics subsystem:

struct AnalyticsLogFilter: LogFilter {
    let name = "analytics"
    
    func shouldInclude(_ message: LogMessage, logLevel: LogLevel) -> Bool {
        // only consider those with a given attribute
        guard message.attributes["subsystem"] == "analytics" else { return true }
        
        return logLevel != .debug
    }
    
    func shouldInclude(_ message: String, logLevel: LogLevel) -> Bool {
        // we don't have any additional context for string messages, so always include
        return true
    }
}

With this filter you can now conditionally add this to the logger:

logger.addFilter(AnalyticsLogFilter())

Or later if you want to remove it:

logger.removeFilter(named: "analytics")
// or 
logger.removeFilters()

Messages that return false from the filter will not be emitted.

Changing log levels at runtime

It can be advantageous in DEBUG and ADHOC builds to allow testers to change the log level to include messages that would otherwise be too noisy to include by default.

You can change the log level at runtime by calling logger.setLogLevels(...). Note that this is passed an OptionSet, so you need to include all of the log levels you want to include.

If you are using the default set of options, you can use the .minimum helper method to include all levels above a given log level. For instance, to include .info and above:

logger.setLogLevels(.minimum(.info))

This method is not supported if you are using custom log levels.

FAQ

Why 5 default log levels? And why are they so named?

Simple...simplicity and elegance. Contextually it gets difficult to understand which log level you need if you have too many. However, that doesn't mean that this is always the perfect solution for everyone or every use case. This is why there are 5 default log levels, with support for easily adding additional ones.

As for the naming, here's our mental breakdown of each log level for an iOS app (obviously it depends on your use case).

  • debug - Highly detailed information of a context
  • info - Summary information of a context
  • event - User driven interactions such as button taps, view transitions, selecting a cell
  • warn - An error occurred but it is recoverable
  • error - A non-recoverable error occurred

When should I use Willow?

If you are starting a new iOS project in Swift and want to take advantage of many new conventions and features of the language, Willow would be a great choice. If you are still working in Objective-C, a pure Objective-C library such as CocoaLumberjack would probably be more appropriate.

Where did the name Willow come from?

Willow is named after the one, the only, Willow tree.


License

Willow is released under the MIT license. See LICENSE for details.

Creators

willow's People

Contributors

alihen avatar atomiccat avatar cnoon avatar colbylwilliams avatar dependabot[bot] avatar ejensen avatar ericappel avatar gtrop1 avatar infinisil avatar purrden avatar subdigital avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

willow's Issues

Type not displayed in Console output on Mac for OSLogWriter

I am using Willow v6.0.0. In it, I am creating a release level logger like this:

private static func buildReleaseLogger(name: String) -> Logger {
        guard let bundleIdentifier =  Bundle.main.bundleIdentifier else {
            return buildDebugLogger(name: name)
        }
        
        let osLogWriter = OSLogWriter(subsystem: bundleIdentifier, category: name)
        
        let appLogLevels: LogLevel = [.event, .info, .warn, .error]
        let asynchronousExecution: Logger.ExecutionMethod = .asynchronous(
            queue: DispatchQueue(label: "speech-drill.logging", qos: .utility)
        )
        
        return Logger(logLevels: appLogLevels, writers: [osLogWriter], executionMethod: asynchronousExecution)
}

But when I open the console app on my Mac and change the build configuration to release, I see the type field empty when filtering by subsystem.

image

What am I missing in this setup? I have followed this guide: Convenient Logging in Swift and used the exact same code. The only changes are made in subsystem and queue label names. In the output for the tutorial, you can see the type of log which gets decided by log level. What am I missing?

This configure function is called in application(_:didFinishLaunchingWithOptions:) .

static func configure() {
        
        let name = "Logger"
       
        #if DEBUG
            willow_logger = buildDebugLogger(name: name)
        #else
            willow_logger = buildReleaseLogger(name: name)
        #endif
        
        willow_logger?.enabled = true
}

I have some suggestions

Recently, I try to found a logging library written in Swift.
Such as XCGLogger, SwiftyBeaver can`t satisfy me.

Talk about Willow, I must say, your shoe is very good , so your code must be good.

First Willow dont have a way to log to file.
Second, I think func info(message: () -> String) is not very good, I suggest this:

func lInfo(items: Any..., separator: String = " ") {
    let str = items.reduce("") { return $0 + "\($1)" + separator }
    info (str)
}

So it will use like print(1, 2, "21", [1, 2, 3])

Colored Console Output in Xcode 8

For anyone out there that has used XcodeColors in the past or with Willow in Xcode 7, you'll be sad to know that this awesome plugin will no longer work in Xcode 8. Apple has decided to rid the Xcode world of plugins and instead has introduced Xcode extensions.

colored logging output

As of right now, only source code extensions are currently supported. This only allows you to modify the source code of an existing file when running your extension. This does not allow us to modify anything with respect to the Xcode console. If you are as sad as we are at Nike that this will no longer be supported, please duplicate rdar://27513087 to help raise the priority of this feature request.

I'm going to keep this issue open most likely until the Xcode 8 GM is officially released to hopefully raise the visibility of this feature request. If you do duplicate this rdar, please mark this message with the thumbs up or add a comment to this issue so we can help track how many dupes we have out there.

Thank you so much!

OSLogWriter not compiling on macOS

There is an unnecessary preprocessor condition surrounding the OSLogWriter declaration that prevents it from being compiled on macOS.

Is there any meaning behind this? I'd like to know why this has been done this way (cc @cnoon)

PR is #19

Swift 6 - Concurrency

Hello,

I've noticed that part of this library may require updating for the upcoming concurrency changes in Swift 6

After turning on strict concurrency checks I'm seeing the following error in my project for static properties of the LogLevel class:

Static property 'debug' is not concurrency-safe because it is not either conforming to 'Sendable' or isolated to a global actor; this is an error in Swift 6

Relevant guide:

OSLogWriter sends os logs with same type for both warn and error levels

It seems OSLogWriter sends os logs with type error for both warn and error levels.
I think it would be better to have different types for these 2 levels assigning fault type to error level.

In LogWriter.swift at line 186 (on master branch) we have:

        case LogLevel.warn:  return .error
        case LogLevel.error: return .error

we could just modify it in this way:

        case LogLevel.warn:  return .error
        case LogLevel.error: return .fault

SPM Package via Fastlane in Xcode does not work with Willow

Hey Nike,

I know I'm not using SPM incorrectly, because some of the packages/products to get installed and I obviously have higher than macOS.11.

This is the error:

error: the product 'Kingfisher' requires minimum platform version 10.12 for macos platform
error: the product 'RxSwiftExt' requires minimum platform version 10.11 for macos platform
error: the product 'Willow' requires minimum platform version 10.11 for macos platform

Thank you,
Montana Mendy

Willow 2.0 not available on cocoapods

Hey guys, I'm super excited to start using willow, however I just ran into a small roadblock I thought you might like to know about.

Podfile:

source 'https://github.com/CocoaPods/Specs.git'
project 'CCRewards'

target 'CCRewards' do
    platform :ios, '8.0'
    use_frameworks!

    pod 'Willow', '~> 2.0'
    pod 'Reveal-iOS-SDK', :configurations => ['Debug']

end

Cocoapods (1.0.1) output:

Analyzing dependencies
[!] Unable to satisfy the following requirements:

- `Willow (~> 2.0)` required by `Podfile`

None of your spec sources contain a spec satisfying the dependency: `Willow (~> 2.0)`.

You have either:
 * out-of-date source repos which you can update with `pod repo update`.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.

I ran pod repo update but that did not fix the issue

Willow on cocoapods.org:
https://cocoapods.org/pods/Willow
Shows version is 1.1.0

Thanks in advance for your help and all your hard work!

Passing FileName and LineNumber

open func error(_ message: @autoclosure @escaping () -> LogMessage) {

I don't see a way to attach the file name and line number to the logs, which would be useful for errors especially. Is this something you've considered and discarded or just something you haven't needed? I'm going to add it to my project, if it's something you're interested in, I'd be happy to make a PR at add this. This is basically the code:

// function
    open func error(_ message: @autoclosure @escaping () -> LogMessage, _ file: String = #file, _ line: Int = #line) {
        print("file = \(file)\nline = \(line)")
        logMessage(message, with: LogLevel.error)
    }

// function call (unchanged)
log.error(Message.requestFailed(request: request, response: fakeResponse, error: nil))

// resulting output
file = /Users/.../Desktop/Willow-5.1.0 2/Example/Frameworks/Database/Connection.swift
line = 63
2019-07-31 12:27:57.744 ๐Ÿ’ฃ๐Ÿ’ฅ๐Ÿ’ฃ๐Ÿ’ฅ [Database] => SQL Error: ["error_description": "The database file is locked", "framework_name": "Database", "result": "failure", "framework_version": "1.0", "sql": "CREATE TABLE cars(make TEXT NOT NULL, model TEXT NOT NULL)", "error_code": 5]

This would be especially helpful when creating a LogWriter to post logs to a server. That way you can determine error locations based on logs.

Feature request: Linux support

I saw the previous issue and related PR to add a minimum of Linux support:

I understand Nike wouldn't find Linux support useful internally so totally get not taking the time to build this feature, but I personally would like to see it. Does the Nike team have any thoughts on how they'd like to see this support implemented in a way it could be maintained by the core team in the future?

Impossible to compile on linux

Hello,

The LogWriter imports without condition the os module, and uses %@ to print strings to NSLog.

The os module and the %@ formatter are not available in Foundation, therefore it is not possible to build on Linux and do some server-side swift using Willow on Linux platform.

Here is the kind of errors you get when you try:

/src/Lambda/.build/checkouts/Willow.git-2002761449145563439/Source/LogWriter.swift:26:8: error: no such module 'os'
import os
       ^

and

/src/Lambda/.build/checkouts/Willow.git--433062434768024296/Source/LogWriter.swift:124:34: error: argument type 'String' does not conform to expected type 'CVarArg'
        case .nslog: NSLog("%@", message)
                                 ^~~~~~~
                                         as! CVarArg

I suggest to add a condition on the os import using canImport() and around the OSLogWriter class.

About the string formatter, we can use withCString and %s. Bad solution, destroys unicode char because %s forces roman charset. Replaced with the usage of NSLog without the formatter, it works.

I made a pull request (#52) implementing this, and built it on both MacOS and Linux, so these few changes make it entirely usable on Linux.

I hope I respected all the requirements, do not hesitate to tell me if I did anything wrong. Also I'm not a native english speaker and there may be some language mistakes, sorry about that.

Managing os_log <private> logging

It seems that because the OSLogWriter wraps os_log, all log messages are handled as format arguments and thus when not actively debugging an app. This substantially reduce the value of release build os_log. It also makes it impossible to separate a developer's own formatted arguments from accompanying static text.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.