Coder Social home page Coder Social logo

swiftybeaver / swiftybeaver Goto Github PK

View Code? Open in Web Editor NEW
5.9K 5.9K 477.0 2.43 MB

Convenient & secure logging during development & release in Swift 4 & 5

Home Page: https://swiftybeaver.com

License: MIT License

Swift 98.75% Ruby 0.84% Shell 0.29% Dockerfile 0.11%
apple-tv ios logging macos server-side-swift swift swift-framework swift4 swift5 swiftybeaver-platform vapor

swiftybeaver's Introduction

Colorful, flexible, lightweight logging for Swift 3, Swift 4 & Swift 5.
Great for development & release with support for Console, file & cloud destinations for server-side Swift.

Language Swift 2, 3, 4 & 5 CircleCI



During Development: Colored Logging to Xcode Console via OSLog API or Print

image

In Xcode 15

// use Apple's fancy OSLog API:
let console = ConsoleDestination()
console.logPrintWay = .logger(subsystem: "Main", category: "UI")

// or use good ol' "print" (which is the default):
let console = ConsoleDestination()
console.logPrintWay = .print

In Xcode 8

Learn more about colored logging to Xcode 8 Console with Swift 3, 4 & 5. For Swift 2.3 use this Gist. No need to hack Xcode 8 anymore to get color. You can even customize the log level word (ATTENTION instead of ERROR maybe?), the general amount of displayed data and if you want to use the 💜s or replace them with something else 😉


During Development: Colored Logging to File

Learn more about logging to file which is great for Terminal.app fans or to store logs on disk.


Google Cloud & More

You can fully customize your log format, turn it into JSON, or create your own destinations. For example, our Google Cloud Destination is just another customized logging format that adds the powerful functionality of automatic server-side Swift logging when hosted on Google Cloud Platform.





Installation

  • For Swift 4 & 5 install the latest SwiftyBeaver version
  • For Swift 3 install SwiftyBeaver 1.8.4
  • For Swift 2 install SwiftyBeaver 0.7.0

Carthage

You can use Carthage to install SwiftyBeaver by adding that to your Cartfile:

Swift 4 & 5:

github "SwiftyBeaver/SwiftyBeaver"

Swift 3:

github "SwiftyBeaver/SwiftyBeaver" ~> 1.8.4

Swift 2:

github "SwiftyBeaver/SwiftyBeaver" ~> 0.7

Swift Package Manager

For Swift Package Manager add the following package to your Package.swift file. Just Swift 4 & 5 are supported:

.package(url: "https://github.com/SwiftyBeaver/SwiftyBeaver.git", .upToNextMajor(from: "2.0.0")),

CocoaPods

To use CocoaPods just add this to your Podfile:

Swift 4 & 5:

pod 'SwiftyBeaver'

Swift 3:

target 'MyProject' do
  use_frameworks!

  # Pods for MyProject
  pod 'SwiftyBeaver', '~> 1.8.4'
end

Swift 2:

target 'MyProject' do
  use_frameworks!

  # Pods for MyProject
  pod 'SwiftyBeaver', '~> 0.7'
end

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    # Configure Pod targets for Xcode 8 with Swift 2.3
    config.build_settings['SWIFT_VERSION'] = '2.3'
  end
end


Usage

Add that near the top of your AppDelegate.swift to be able to use SwiftyBeaver in your whole project.

import SwiftyBeaver
let log = SwiftyBeaver.self

At the beginning of your AppDelegate:didFinishLaunchingWithOptions() add the SwiftyBeaver log destinations (console, file, etc.), optionally adjust the log format and then you can already do the following log level calls globally:

// add log destinations. at least one is needed!
let console = ConsoleDestination()  // log to Xcode Console
let file = FileDestination()  // log to default swiftybeaver.log file

// use custom format and set console output to short time, log level & message
console.format = "$DHH:mm:ss$d $L $M"
// or use this for JSON output: console.format = "$J"

// In Xcode 15, specifying the logging method as .logger to display color, subsystem, and category information in the console.(Relies on the OSLog API)
console.logPrintWay = .logger(subsystem: "Main", category: "UI")
// If you prefer not to use the OSLog API, you can use print instead.
// console.logPrintWay = .print 

// add the destinations to SwiftyBeaver
log.addDestination(console)
log.addDestination(file)

// Now let’s log!
log.verbose("not so important")  // prio 1, VERBOSE in silver
log.debug("something to debug")  // prio 2, DEBUG in green
log.info("a nice information")   // prio 3, INFO in blue
log.warning("oh no, that won’t be good")  // prio 4, WARNING in yellow
log.error("ouch, an error did occur!")  // prio 5, ERROR in red

// log anything!
log.verbose(123)
log.info(-123.45678)
log.warning(Date())
log.error(["I", "like", "logs!"])
log.error(["name": "Mr Beaver", "address": "7 Beaver Lodge"])

// optionally add context to a log message
console.format = "$L: $M $X"
log.debug("age", context: 123)  // "DEBUG: age 123"
log.info("my data", context: [1, "a", 2]) // "INFO: my data [1, \"a\", 2]"

Alternatively, if you are using SwiftUI, consider using the following setup:

import SwiftyBeaver
let logger = SwiftyBeaver.self

@main
struct yourApp: App {

    init() {
        let console = ConsoleDestination()
        logger.addDestination(console)
        // etc...
    }

    var body: some Scene {
        WindowGroup {
        }
    }
}


Server-side Swift

We ❤️ server-side Swift 4 & 5 and SwiftyBeaver support it out-of-the-box! Try for yourself and run SwiftyBeaver inside a Ubuntu Docker container. Just install Docker and then go to your project folder on macOS or Ubuntu and type:

# create docker image, build SwiftyBeaver and run unit tests
docker run --rm -it -v $PWD:/app swiftybeaver /bin/bash -c "cd /app ; swift build ; swift test"

# optionally log into container to run Swift CLI and do more stuff
docker run --rm -it --privileged=true -v $PWD:/app swiftybeaver

Best: for the popular server-side Swift web framework Vapor you can use our Vapor logging provider which makes server logging awesome again 🙌



Documentation

Getting Started:

Logging Destinations:

Advanced Topics:



License

SwiftyBeaver Framework is released under the MIT License.

swiftybeaver's People

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  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

swiftybeaver's Issues

Format of string in console.

Hi, i have a little problem with the format output in console. this is my output.

[2015-12-10 14:44:59.071] AppDelegate.application(_:didFinishLaunchingWithOptions:):24 [fg200,200,200;VERBOSE[;: Nothing really happened

i have installed XcodeColors and use the las version of SwiftyBeaver (Manually)

Flexible level name

A user can, for example, replace the default error level string "ERROR" with "OMG!"

Unable to subclass BaseDestination

I am perhaps being dense, but how exactly can one subclass BaseDestination in order to override the requisite methods when those methods are not public?

Injectable log destinations

I saw that you have pretty hard-coded handlers for console and file destinations, but:

1- It's not flexible enough
2- It's not scalable

What if I want to have a Bonjour destination or a remote HTTP endpoint one?
It could be nice to setup a logger to log to multiple configured destinations (even multiple files, for example)

Praise, request and a question

Praise

First off, how did we live prior to SwiftyBeaver? Seems impossible to live without now!

Request

It would be awesome to hide or delete log items? logs will grow beyond control after a while.

Question

When I try to log to SBPlatformDestination, it won't be flushed until my next launch! is it intentional? Am I missing something? They don't appear on SwiftBeaver Mac App until my iOS apps next launch. Got it, it was the threshold thing!

Which Next Custom Destination?

Currently SwiftyBeaver supports Xcode Console & file as logging destinations.

What should be the next destination?

P.S.: Maybe the destinations should be renamed to beaver lodge - you know, where he brings the logs to 🏠

Colors not showing in Xcode console

Not that this is actually bothering me as I much rather use the tail method in iTerm, but this is still a bug:
as stated in the title, colors are not showing in the Xcode console. Instead I get the following:

[2015-12-16 10:25:20.787] AppDelegate.application(_:didFinishLaunchingWithOptions:):103 �[fg0,0,255;DEBUG�[;: something to debug [2015-12-16 10:25:20.790] AppDelegate.application(_:didFinishLaunchingWithOptions:):104 �[fg0,255,0;INFO�[;: a nice information [2015-12-16 10:25:20.791] AppDelegate.application(_:didFinishLaunchingWithOptions:):105 �[fg255,255,0;WARNING�[;: oh no, that won’t be good [2015-12-16 10:25:20.791] AppDelegate.application(_:didFinishLaunchingWithOptions:):106 �[fg255,0,0;ERROR�[;: ouch, an error did occur! [2015-12-16 10:25:20.792] AppDelegate.application(_:didFinishLaunchingWithOptions:):109 �[fg200,200,200;VERBOSE�[;: 123 [2015-12-16 10:25:20.792] AppDelegate.application(_:didFinishLaunchingWithOptions:):110 �[fg0,255,0;INFO�[;: -123.45678 [2015-12-16 10:25:20.792] AppDelegate.application(_:didFinishLaunchingWithOptions:):111 �[fg255,255,0;WARNING�[;: 2015-12-16 09:25:20 +0000 [2015-12-16 10:25:20.792] AppDelegate.application(_:didFinishLaunchingWithOptions:):112 �[fg255,0,0;ERROR�[;: ["I", "like", "logs!"] [2015-12-16 10:25:20.835] AppDelegate.application(_:didFinishLaunchingWithOptions:):113 �[fg255,0,0;ERROR�[;: ["address": "7 Beaver Lodge", "name": "Mr Beaver"]

OSX version: el Capitan
XCode version: 7.2

And thanks for a wonderful tool that rocks my world!

Shouldn't the default file destination be the Cache directory?

Currently the FileDestination class save a log file in the Documents directory of the app.
Since there is no control for the file size (this could be a different issue actually), the file could grow indefinitely.
Considering that the documents directory is backed up to iCloud, the cache directory in my opinion would be a better location.

Setup using the instructions

ce5yoc5w8aa55dh jpg-large
Having followed the documentation for manual install Xcode is flagging up the datatypes used in the code I copied from the instrcutions.

More Unit Tests

At least every function with a return value needs to be tested.

Add support for printing current thread

Printing the current thread would be useful information for debugging things (like core data). Similar to what is possible in XCGLogger. This is how they are doing it.

        if showThreadName {
            if NSThread.isMainThread() {
                extendedDetails += "[main] "
            }
            else {
                if let threadName = NSThread.currentThread().name where !threadName.isEmpty {
                    extendedDetails += "[" + threadName + "] "
                }
                else if let queueName = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)) where !queueName.isEmpty {
                    extendedDetails += "[" + queueName + "] "
                }
                else {
                    extendedDetails += "[" + String(format:"%p", NSThread.currentThread()) + "] "
                }
            }
        }

Strange output

Added SwiftyBeaver (v.0.3), but in output getting this:

[19:26:54] �[fg255,0,0;ERROR�[;: Error

Source

log.error("Error")    

Linking against watchOS Target is not working

Hey there,

i integrate your awesome framework successfully into OSX and iOS Applications. But i have trouble running them on an iPhone while including a watch extension. It is working fine on the simulator but is crashing because of the following problem:

(null): Linking against dylib not safe for use in application extensions: /.../em_swift_ios/Carthage/Build/watchOS/SwiftyBeaver.framework/SwiftyBeaver

I first encountered it while linking your framework with my own framework (which also includes a watchOS target) where it was throwing a code signing error because of the dylib linking shown in the error above.

Maybe someone has a clue to solve this problem? I'm pretty new to the code signing stuff myself.

Ideas around logging and frameworks

Our application is split into quite a few frameworks. Our ideal logging solution would be something that allows us to change logging verbosity per framework (using CocoaPods). With a global variable in the AppDelegate I don't see how the frameworks could access it or have logging at all?

This is possible with CocoaLumberjack and Objective-C but it requires using macros. I'm not sure how or if this sort of logging can happen with the approach. Any ideas on this?

Log all types

Currently variables need to embedded in "(foo)" to be printed because the log level functions just accept Strings.

That should be changed to accept everything (Any / AnyObject) and the printable version of the object should be logged.

Have ability to disable colors

In #19 we will be supporting logging to the terminal which does not have support for the xcode colors plugin.

Ideally when initialising the console destination we should be able to pass a bool to disable this plugin.

File-based logging levels

Gentlefolk,

In Objective-C, I could build a simple macro around NSLog that allowed me to turn logging on/off on a per file basis. This allowed me to keep logging rich source code base while turning off logging for most of my project. This dramatically reduced the noise in my logs while I'm building and debugging features.

Can SwiftyBeaver be made to do this?

Anon,
Andrew

Add Changelog

Start writing a changelog. Release it in a file and additionally use Github’s release tab.

Swift Package Manager package

There's been a good discussion on one of the the Swift mailing lists about a good logging framework. Any chance you could make a Package.swift file?

Change log output behavior from asynchronous to synchronous

Asynchronous log output makes debugging difficult when using the debugger.
For example, set a breakpoint at a line where log is outputted, step over one line, and no log seen in the console.
If the implementation is changed to do synchronous output, it would be great help!

WatchOS Support

After some tries with Cocoapods (where it needs to be declared for a watchOS use) i decided to use carthage, added the frameworks to my project and it still won't work with my Watch Extension classes.

So this is a question and request:

  • Can i use the framework at this state for the watch extension?

If not, please add support for the Watch Extension. :)

Please add public initialize method on LevelString.

Original:

public struct LevelString {
        public var Verbose = "VERBOSE"
        public var Debug = "DEBUG"
        public var Info = "INFO"
        public var Warning = "WARNING"
        public var Error = "ERROR"
    }

Want this.

public struct LevelString {
        public var Verbose = "😬"
        public var Debug = "😀"
        public var Info = "🤔"
        public var Warning = "😥"
        public var Error = "😲"
    }

iphone7

detect the device is wrong i run in iphone6 and it show iphone7 there isn't iphone7 yet
screen shot 2016-06-01 at 6 47 09 pm

Printing variable name and value pair

Hello!!

I thought it'd be useful if we could do like this.

let foobar = 1234
SwiftyBeaver.debugObject(foobar) // will prints "foobar = 1234"

Inspired by https://github.com/inamiy/DebugLog, which has LOG_OBJECT. This works only on Simulators. It fallbacks to LOG on devices, and example above will print "1234".

Are you happy to have me add this feature ?

It's not working for me

the console output is like this
[2015-12-01 14:25:13.784] ViewController.viewDidLoad():22 �[fg255,255,0;WARNING�[;: message

Use @autoclosure for message

Currently when passing in a message, the message needs to be evaluated whether or not the log should be logged.

I would propose changing the signatures of the the log functions to be:

public class func verbose(@autoclosure msg:  () -> Any, _ path: String = __FILE__, _ function: String = __FUNCTION__, line: Int = __LINE__) 

and

class func dispatch_send(level: SwiftyBeaver.Level, @autoclosure msg:  () -> Any, path: String, function: String, line: Int) {

Users would be able to pass in either an object/struct/enum or a closure that returns an object/struct/enum. We should also investigate whether there are any gains in making the path, function, and line also @autoclosures (this might be beneficial to the Objective-C wrapper to lazily grab those values).

In Objective-C, usually this problem would be solved at compile time by the preprocessor.

All logs begin with untidy string "[0;37mV[0m:"

For example
[0;37mV[0m: /Users/xxx/Documents/ add 1

Setup

      let file = FileDestination()
        file.detailOutput = false
        file.levelString.Verbose = "V"
        file.dateFormat = ""
        file.logFileURL =  NSURL(fileURLWithPath: "/Users/x/Documents/x.log")
        Log.addDestination(file)

Make threadName() method public

Hello Sebastian,

you mind making threadName() method public ? I could use this method in my own code too.
you need a PR for this ?

Thanks
Frank

"Do not have permission" Error when trying to save into /tmp (even after sudo chmod 777 /temp)

[Using Xcode 7.3]

So I wanted to write into temp:

file.logFileURL = NSURL(string: "file:///tmp/neko.log")!

But I got this error that I don't have the permission to do so:

SwiftyBeaver could not write to file file:///tmp/neko.log. Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file "neko.log” in the folder “tmp”." UserInfo={NSFilePath=/tmp/app_info.log, NSUnderlyingError=0x129877180 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I even did sudo chmod 777 /temp but it didn't help.

I was running the app on an iPad (due to some constraints the app isn't testable in a simulator). Can it be that it is trying to write into /tmp on the iPad instead?

If that is the case, is there a way to get it to write into the /tmp on my El Capitan?

Introducing the SwiftyBeaver Logging Platform

Fellow contributors & users,

I am more than happy to announce the free private beta release of the new SwiftyBeaver Logging Platform. It adds all the missing pieces of a complete logging solution which can be used hassle-free during development and release.

True end-to-end encryption, a dedicated crypto cloud, a Mac App, native Swift 2 support and the collection of new** analytics** data should help all of us getting more insights into how our apps perform and how our users are actually using it.

But read for yourself, I put the most important aspects into a short 2 minute article on Medium.

A Note to All Contributors

I want to personally thank you for your help, ideas, discussions and time over the last months which made the transformation from a great logging framework (your work guys!) into a real venture with a solid value proposition for Swift developers just possible. You ignited and endorsed the idea of a logging platform for Swift and I am so happy to have it in a state to finally show it to you for input and feedback.

Of course, there are still many things to do but we can now build onto a mighty, growing platform and It would make me super happy if you all continue your efforts in making SwiftyBeaver into the best logging solution for all of us.

The next tasks are the finalizing of the new platform destination and especially your ideas how to make everything even better, adding more destinations and services, etc.

For that purpose will introduce an invite-only Slack channel where we can all discuss more efficiently.

Next Steps

Please put your email on the private beta waiting list and send me your email via Twitter DM @skreutzb so that I can prioritize your registration. I will send you then an invite to the Slack channel and information how to get your hands on the new platform destination and the Mac App.

I am very excited and am looking forward to a successful private beta.

Thank you all & Happy Logging!

Travis failing under Xcode 7.3

Can anyone fix that? I just upgraded the source code to support Xcode 7.3, Swift 2.2 and Swift 3 (as stated by Xcode) and now the Travis tests are failing. Thanks!

Objective-C Wrapper and KZLinkedConsole

Hey,

We just started using SwiftyBeaver as our logging library — thanks!

We have a bunch of Objective-C code that we aren't going to rewrite anytime soon but would like to be able to add some logging to.

I don't think this project needs to have an Objective-C wrapper included but it would be beneficial as a separate project that someone could add if they needed.

I have a basic wrapper and macros here: SwiftyBeaverObjectiveC

The only thing I am having an issue with is formatting the Objective-C functions to work with KZLinkedConsole.

Here is the output using the standard FUNCTION string:

[2015-12-19 17:21:05.910] ViewController.-[ViewController logInfo:]:28 [fg0,255,0;INFO[;: This is an info message.

So I'm not sure how the formatting could be modified so that hit would work with the Objective-C style method names? I could do some extra work to make the Objective-C method names print out like the swift style but that seems like a bad idea. Do you see anyway that the formatting could be changed so that it is more agnostic about the language the function is in?

Color coding should be in the ConsoleDestination, not in BaseDestination

I believe color coding is useful only in the console but not in any other situations.
I would move it to the ConsoleDestination class so that when subclassing BaseDestination the color coding is excluded and the default logs do not include that.
Right now, when writing to a log file, it's necessary to specify colored=true otherwise the logs include the color coding and are hard to read.
If there is a particular reason why the color coding is in the base class, I apologize.

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.