sorin
sorin

Reputation: 170440

How can I control error level of NSLog messages on iOS?

I observed the NSLog() does log all my messages with error level Warning but when I look to the console I see other messages with different error levels like Info, or `Error.

How can I control the error level of my messages?

Upvotes: 13

Views: 7973

Answers (3)

Joule87
Joule87

Reputation: 651

Another possible option you could use as a replacement for NSLog is OSLog, it comes with some nice advantages, is flexible and easy to use. For using it create an OSLog extension to set some configurations:

import Foundation
import os.log

extension OSLog {
    private static var subsystem = Bundle.main.bundleIdentifier!

    /// Defining my custom log objects
    /// Log View Cycles.
    static let viewCycle = OSLog(subsystem: subsystem, category: "View Cycle")
    /// Log User Actions.
    static let userAction = OSLog(subsystem: subsystem, category: "User Action")
}

Then just use it whenever you want in your View Controllers:

 import UIKit
 import os.log

 class MenuViewController: UIViewController {

   @IBAction func didTapMenu(_ sender: UIBarButtonItem) {
      os_log("Did tap %@ option", log: .userAction, type: .info, "Some UI element")
   }
}

As you can see you can specify a log level as a type parameter and define your own custom log objects.

Console Output: 2019-12-11 10:21:44.788204-0300 ProjectName[70193:3015307] [User Action] Did tap Some UI element option

Upvotes: 2

Hans
Hans

Reputation: 2262

Use the ASL log:

asl_log(NULL, NULL, ASL_LEVEL_INFO, "Hello World!!!");

Where the ASL_LEVEL_INFO can be any of these:

ASL_LEVEL_EMERG 
ASL_LEVEL_ALERT
ASL_LEVEL_CRIT
ASL_LEVEL_ERR
ASL_LEVEL_WARNING
ASL_LEVEL_NOTICE
ASL_LEVEL_INFO
ASL_LEVEL_DEBUG

Upvotes: 6

rickerbh
rickerbh

Reputation: 9911

I don't believe you can alter the logging level of NSLog() messages. You can use 3rd party logging solutions (or write your own macro) to insert different error level strings into the logs that can then be filtered on.

Check out the following libraries for pre-built logging solutions.

Upvotes: 9

Related Questions