• Stars
    star
    298
  • Rank 139,663 (Top 3 %)
  • Language
    Objective-C
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Twitter Logging Service is a robust and performant logging framework for iOS clients

Twitter Logging Service

Background

Twitter created a framework for logging in order to fulfill the following requirements:

  • fast (no blocking the main thread)
  • thread safe
  • as easy as NSLog in most situations
  • support pluggable "output streams" to which messages will be delivered
  • "output streams" filter messages rather than global filtering for all "output streams"
  • able to categorize log messages (log channels)
  • able to designate importance to log messages (log levels)
  • require messages to opt-in for persisted logs (a security requirement, fulfilled by using the context feature of TLS)

Twitter has been using Twitter Logging Service since January 2014 with minimal changes. We've decided to share it with the developer community.

List of good alternative logging frameworks

If Twitter Logging Service doesn't meet your needs, there are many great logging frameworks available, including the following high quality and well maintained projects:

  • CocoaLumberjack
  • SwiftyBeaver
  • Apache Logging Services

Architecture

There are 3 components to consider:

  1. the log message and its context
  2. the logging service instance or singleton
  3. the output stream(s)

The log message is sent to the logging service which provides the message to each output stream.

The logging service is configured by adding discrete output streams. Output streams encapsulate their own behavior and decisions, including filtering and logging messages. For instance, logging can mean printing to console with NSLog, writing to a file on disk, or sending the message to a remote server.

Message arguments don't need to be evaluated if the message is going to be filtered out. This avoids expensive, synchronous execution of argument evaluation. The message is then packaged with context before it is sent to the logging service. Context includes information such as the log level, log channel, file name, function name, line number and timestamp.

The logging service marshals the message and its context to a background queue for processing by all available output streams. Streams can then filter or output the message.

Installation

CocoaPods

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

    $ gem install cocoapods

To integrate TwitterLoggingService into your Xcode project using CocoaPods, specify it in your Podfile:

    platform :ios, '8.0'
    use_frameworks!

    target "MyApp" do
        pod 'TwitterLoggingService', '~> 2.9.0'
    end

Usage

TLSLog.h is the principal header for using TwitterLoggingService. Just include TLSLog.h or @import TwitterLoggingService.

    // The primary macros for *TwitterLoggingService*

    TLSLogError(channel, ...)          // Log at the TLSLogLevelError level
    TLSLogWarning(channel, ...)        // Log at the TLSLogLevelWarning level
    TLSLogInformation(channel, ...)    // Log at the TLSLogLevelInformation level
    TLSLogDebug(channel, ...)          // Log at the TLSLogLevelDebug level

For each macro in the TLSLog family of macros, TLSCanLog is called first to gate whether the actual logging should occur. This saves us from having to evaluate the arguments to the log message and can provide a win in performance when calling a TLSLog macro that will never end up being logged. For more on TLSCanLog see Gating TLSLog messages below.

TLSLog Core Macro

    #define TLSLog(level, channel, ...)

TLSLog is the core macro and takes 3 parameters: a TLSLogLevel level, an NSString channel and then an NSString format with variable formatting arguments. The level and channel parameters are used to filter the log message per TLSOutputStream in the TLSLoggingService singleton. Providing nil as the channel argument to any logging macro, function or method will result in the message not being logged.

Logging Channels, Levels and Context Objects

Channels

The logging channel of a log message is an arbitrary string and acts as a tag to that message to further help identify what the message relates to. Channels can help to quickly identify what a log message relates to in a large code base, as well as provide a mechanism for filtering. A TLSOutputStream can filter based on the logging channel in its implementation of tls_shouldFilterLevel:channel:contextObject:. Providing a nil channel to a log statement has the effect of not logging that message.

Examples of potential logging channels: @"Networking" for the networking stack, @"SignUp" for an app’s signup flow, TLSLogChannelDefault as a catch all default logging channel, and @"Verbose" for anything you just want to log for the helluvit.

Levels

The enum TLSLogLevel specifies 8 logging levels in accordance with the syslog specification for logging. For practical use, however, only 4 log levels are used: TLSLogLevelError, TLSLogLevelWarning, TLSLogLevelInformation and TLSLogLevelDebug. Each log message has a specified logging level which helps quickly identify its level, TLSLogLevelEmergency (or TLSLogLevelError in practice) is the most important while TLSLogLevelDebug is the least. TLSOutputStream instances can filter a log message by its log level (in combination with its logging channel and context object) by implementing tls_shouldFilterLevel:channel:contextObject:.

An implementation detail to keep in mind w.r.t. logging levels is that TLSLogLevelDebug is ALWAYS filtered out in non-DEBUG builds.

Context Objects

Though the TLSLog macros do not have a context object parameter, one can provide a context object to the TLSLogging APIs in order to provide additional context to custom TLSOutputStreams. The context object will carry through the TLSLoggingService so that it is available to all TLSOutputStream instances. The context object can be used to filter in the tls_shouldFilterLevel:channel:contextObject: method. The context object can also be used for additional information in the logging of a message since it carries to the TLSLogMessageInfo object that's passed to tls_outputLogInfo:.

This context object provides near limitless extensibility to the TLSLogging framework beyond the basics of filtering and logging based on a logging level and logging channel. Twitter uses the context object as a way to secure log messages from leaking to output streams that should not log messages unless explicitely told to do so, thus protecting Personally Identifiable Information from being logged as a default behavior.

Setup

Setting up your project to use TwitterLoggingService:

  1. Add the TwitterLoggingService XCode project as a subproject of your XCode project.

  2. Add the libTwitterLoggingService.a library or TwitterLoggingService.framework framework as a dependency in your XCode project.

  3. Set up your project to build the TwitterLoggingService project with DEBUG=1 in debug builds and RELEASE=1 in release builds.

  4. Set up the TLSLoggingService singleton on application startup (often in application:didFinishLaunchingWithOptions: of your UIApplication's delegate for iOS).

    @import TLSLoggingKit;

    // ...

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
    {
        // ...

        // Set up the Twitter Logging Service!
        TLSLoggingService *logger = [TLSLoggingService sharedInstance];
    #if DEBUG
        if ([TLSOSLogOutputStream supported]) {
            [logger addOutputStream:[[TLSOSLogOutputStream alloc] init]];
        } else {
            [logger addOutputStream:[[TLSNSLogOutputStream alloc] init]];
        }
    #endif
        [logger addOutputStream:[[TLSFileOutputStream alloc] initWithLogFileName:@"appname-info.log"]];

        // ...
    }

    // ...

    // Someplace else in your project
    - (void)foo
    {
        //  ...

        if (error) {
            TLSLogError(TLSLogChannelDefault, @"Encountered an error while performing foo: %@", error);
        } else {
            TLSLogInformation(@"Verbose", @"foo executed flawlessly!");
        }

        // ...
    }

Best Practices

As a best practice follow these simple guidelines:

  1. Any user sensitive information should not be logged to output streams that persist messages (including being sent over the network to be saved). You can configure your output stream to filter out logs to these sensitive channels. Or do the inverse, and only permit certain "safe" channels to be logged. Twitter has elected to use the pattern where only explicitely "safe" messages (designated via a custom context object) are logged to output streams that will persist. If in doubt, you can log to the TLSLogLevelDebug log level, which is only ever logged in DEBUG builds.

  2. Configure DEBUG builds to have a console output like TLSNSLogOutputStream or TLSStdErrOutputStream - but add only 1 or you'll spam the debug console.

  3. Configure RELEASE builds to not use the console output stream.

  4. Add Crashlytics to your project and add a subclass of the TLSCrashlyticsOutputStream to TLSLoggingService instead of using CLSLog, CLSNSLog or CLS_LOG. You MUST subclass TLSCrashlyticsOutputStream.

TLSLogChannelApplicationDefault function

    FOUNDATION_EXTERN NSString *TLSLogChannelApplicationDefault() __attribute__((const));
    #define TLSLogChannelDefault TLSLogChannelApplicationDefault()

Retrieve a channel based on the application. You can use this as a default channel.

Loads and caches the channel name in the following order of descending priority:

  1. kCFBundleNameKey of main bundle

  2. kCFBundleExecutableKey of main bundle

  3. Binary executable name

  4. @"Default"

The default channel is available as a convenience for quick logging. However, it is recommended to always have concrete, well-defined logging channels to which output is logged (e.g. "Networking", "UI", "Model", "Cache", et al).

TLSLog Helper Functions

There are a number of TLSLog Helper Functions and they all accept as a first parameter a TLSLoggingService. If nil is provided for the service parameter, the shared [TLSLoggingService sharedInstance] will be used. All TLSLog macros use nil for the service parameter, but if there is different instance to be used, these helper functions support that. As an example, Twitter extends TwitterLoggingService with its own set of macros so that a context is provided that defines the duration for which a message can be safely retained (e.g. to avoid retaining sensitive information), and uses custom macros that call these helper functions.

Gating TLSLog messages

    BOOL TLSCanLog(TLSLoggingService *service, TLSLogLevel level, NSString *channel, id contextObject); // gate for logging TLSLog messages

At the moment, TLSCanLog evaluates two things (contextObject is currently ignored): the cached permitted log levels and the cached not permitted log channels. A log message can log given the desired level is permitted by the internal cache of known permitted TLSLogLevels based on the outputStreams of TLSLoggingService AND the given log channel has not been cached as a known to be an always off channel (for TLSLOGMODE=1 that is, see below for different behaviors).

TLSCANLOGMODE build setting

TwitterLoggingService supports being compiled in one of 3 different modes:

  • TLSCANLOGMODE=0
  • TLSCanLog will always return YES
  • Log arguments always evaluate, which can be inefficient for args that won't log
  • TLSCANLOGMODE=1
  • TLSCanLog will base its return value on cached insight into what can and cannot be logged
  • This will save on argument evalution at the minimal cost of a quick lookup of cached information
  • This is the default if TLSCANLOGMODE is not defined
  • TLSCANLOGMODE=2
  • TLSCanLog will base its return value on the filtering behavior of all the registered output streams
  • This will save on argument evalution but requires an expensive examination of all output streams

License

Copyright 2013-2020 Twitter, Inc.

Licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0

Security Issues?

Please report sensitive security issues via Twitter's bug-bounty program (https://hackerone.com/twitter) rather than GitHub.

More Repositories

1

the-algorithm

Source code for Twitter's Recommendation Algorithm
Scala
61,982
star
2

twemoji

Emoji for everyone. https://twemoji.twitter.com/
HTML
16,768
star
3

typeahead.js

typeahead.js is a fast and fully-featured autocomplete library
JavaScript
16,515
star
4

twemproxy

A fast, light-weight proxy for memcached and redis
C
12,115
star
5

the-algorithm-ml

Source code for Twitter's Recommendation Algorithm
Python
10,027
star
6

finagle

A fault tolerant, protocol-agnostic RPC system
Scala
8,769
star
7

hogan.js

A compiler for the Mustache templating language
JavaScript
5,139
star
8

labella.js

Placing labels on a timeline without overlap.
JavaScript
3,880
star
9

scala_school

Lessons in the Fundamentals of Scala
HTML
3,708
star
10

AnomalyDetection

Anomaly Detection with R
R
3,551
star
11

scalding

A Scala API for Cascading
Scala
3,497
star
12

twitter-text

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.
HTML
3,072
star
13

opensource-website

Twitter's open source website, identifying projects we've released, organizations we support, and the work we do to support open source.
SCSS
2,998
star
14

TwitterTextEditor

A standalone, flexible API that provides a full-featured rich text editor for iOS applications.
Swift
2,976
star
15

util

Wonderful reusable code from Twitter
Scala
2,686
star
16

algebird

Abstract Algebra for Scala
Scala
2,288
star
17

finatra

Fast, testable, Scala services built on TwitterServer and Finagle
Scala
2,272
star
18

effectivescala

Twitter's Effective Scala Guide
HTML
2,242
star
19

summingbird

Streaming MapReduce with Scalding and Storm
Scala
2,138
star
20

pelikan

Pelikan is Twitter's unified cache backend
C
1,936
star
21

ios-twitter-image-pipeline

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients
C
1,854
star
22

twurl

OAuth-enabled curl for the Twitter API
Ruby
1,796
star
23

twitter-server

Twitter-Server defines a template from which services at Twitter are built
Scala
1,567
star
24

rezolus

Systems performance telemetry
Rust
1,564
star
25

communitynotes

Documentation and source code powering Twitter's Community Notes
Python
1,419
star
26

compose-rules

Static checks to aid with a healthy adoption of Compose
Kotlin
1,350
star
27

activerecord-reputation-system

An Active Record Reputation System for Rails
Ruby
1,332
star
28

fatcache

Memcache on SSD
C
1,301
star
29

rsc

Experimental Scala compiler focused on compilation speed
Scala
1,243
star
30

elephant-bird

Twitter's collection of LZO and Protocol Buffer-related Hadoop, Pig, Hive, and HBase code.
Java
1,139
star
31

cassovary

Cassovary is a simple big graph processing library for the JVM
Scala
1,046
star
32

Serial

Light-weight, fast framework for object serialization in Java, with Android support.
Java
998
star
33

hbc

A Java HTTP client for consuming Twitter's realtime Streaming API
Java
961
star
34

vireo

Vireo is a lightweight and versatile video processing library written in C++11
C++
929
star
35

twemcache

Twemcache is the Twitter Memcached
C
929
star
36

innovators-patent-agreement

Innovators Patent Agreement (IPA)
921
star
37

twitter-korean-text

Korean tokenizer
Scala
857
star
38

scrooge

A Thrift parser/generator
Scala
790
star
39

BreakoutDetection

Breakout Detection via Robust E-Statistics
C++
753
star
40

GraphJet

GraphJet is a real-time graph processing library.
Java
705
star
41

twitter-cldr-rb

Ruby implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more.
Ruby
669
star
42

bijection

Reversible conversions between types
Scala
657
star
43

chill

Scala extensions for the Kryo serialization library
Scala
608
star
44

ios-twitter-network-layer

Twitter Network Layer is a scalable and feature rich network layer built on top of NSURLSession for Apple platforms
Objective-C
574
star
45

hadoop-lzo

Refactored version of code.google.com/hadoop-gpl-compression for hadoop 0.20
Shell
545
star
46

storehaus

Storehaus is a library that makes it easy to work with asynchronous key value stores
Scala
464
star
47

rpc-perf

A tool for benchmarking RPC services
Rust
463
star
48

d3kit

D3Kit is a set tools to speed D3 related project development
JavaScript
428
star
49

scoot

Scoot is a distributed task runner, supporting both a proprietary API and Bazel's Remote Execution.
Go
349
star
50

twitter-cldr-js

JavaScript implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more. Based on twitter-cldr-rb.
JavaScript
346
star
51

scala_school2

Scala School 2
Scala
340
star
52

rustcommon

Common Twitter Rust lib
Rust
340
star
53

wordpress

The official Twitter plugin for WordPress. Embed Twitter content and grow your audience on Twitter.
PHP
320
star
54

nodes

A library to implement asynchronous dependency graphs for services in Java
Java
250
star
55

SentenTree

A novel text visualization technique
JavaScript
228
star
56

joauth

A Java library for authenticating HTTP Requests using OAuth
Java
214
star
57

interactive

Twitter interactive visualization
HTML
214
star
58

hpack

Header Compression for HTTP/2
Java
196
star
59

thrift_client

A Thrift client wrapper that encapsulates some common failover behavior
Ruby
196
star
60

cache-trace

A collection of Twitter's anonymized production cache traces.
Shell
168
star
61

zktraffic

ZooKeeper protocol analyzer and stats gathering daemon
Python
167
star
62

twemoji-parser

A simple library for identifying emoji entities within a string in order to render them as Twemoji.
Scala
166
star
63

sbf

Java
162
star
64

tormenta

Scala extensions for Storm
Scala
132
star
65

whiskey

HTTP library for Android (beta)
Java
130
star
66

hraven

hRaven collects run time data and statistics from MapReduce jobs in an easily queryable format
Java
126
star
67

netty-http2

HTTP/2 for Netty
Java
121
star
68

ccommon

Cache Commons
C
99
star
69

sqrl

A Safe, Stateful Rules Language for Event Streams
TypeScript
97
star
70

focus

Focus aligns Git worktree content based on outlines of a repository's Bazel build graph. Focused repos are sparse, shallow, and thin and unlock markedly better performance in large repos.
Rust
92
star
71

metrics

78
star
72

dict_minimize

Access scipy optimizers from your favorite deep learning framework.
Python
77
star
73

twitter.github.io

HTML
71
star
74

diffusion-rl

Python
69
star
75

go-bindata

Go
69
star
76

birdwatch

66
star
77

cloudhopper-commons

Cloudhopper Commons
Java
57
star
78

twitter-cldr-npm

TwitterCldr npm package
JavaScript
49
star
79

.github

Twitter GitHub Organization-wide files
48
star
80

bazel-multiversion

Bazel rules to resolve, fetch and manage 3rdparty JVM dependencies with support for multiple parallel versions of the same dependency. Powered by Coursier.
Scala
47
star
81

libwatchman

A C interface to watchman
C
45
star
82

sslconfig

Twitter's OpenSSL Configuration
43
star
83

ios-twitter-apache-thrift

A thrift encoding and decoding library for Swift
Swift
42
star
84

gatekeeper-service

GateKeeper is a service built to automate the manual steps involved in onboarding, offboarding, and lost asset scenarios.
Python
37
star
85

dodo

The Twitter OSS Project Builder
Shell
35
star
86

repo-scaffolding

Tools for creating repos based on open source standards and best practices
34
star
87

iago2

A load generator, built for engineers
Scala
25
star
88

caladrius

Performance modelling system for Distributed Stream Processing Systems (DSPS) such as Apache Heron and Apache Storm
Python
22
star
89

ossdecks

Repository for Twitter Open Source Decks
10
star
90

curation-style-guide

Document Repository for Twitter's Curation Style Guide
10
star
91

analytics-infra-governance

Description of the process for how to commit, review, and release code to the Scalding OSS family (Scalding, Summingbird, Algebird, Bijection, Storehaus, etc)
9
star
92

gpl-commitment

Twitter's GPL Cooperation Commitment
5
star
93

second-control-probability-distributions

4
star
94

google-tag-manager-base-tag

Smarty
2
star
95

google-tag-manager-event-tag

Smarty
2
star