# Analytics for Clojure

**Support:**

* Community ✓
* Maintenance ✕
* Flagship ✕

Segment doesn't manage or update community libraries. These libraries are available on GitHub under the MIT License for the open-source community to fork or contribute.

The Clojure library lets you record analytics data from your Clojure code. The requests hit Segment servers, and then Segment routes your data to any analytics service you enable on your destinations page.

The library is open-source and was contributed by [CircleCI](https://circleci.com/). You can [check it out on GitHub](https://github.com/circleci/analytics-clj). The Clojure library is a wrapper around Segment's [Java library](https://github.com/segmentio/analytics-java).

The Clojure library (like Segment's other server side libraries) is built for high-performance, so you can use this library in your web server controller code. This library uses an internal queue to make calls non-blocking and fast. It also batches messages and flushes asynchronously to Segment's servers.

## Getting started

Add Analytics for Clojure to your code using Maven and Leiningen.

If you're using Maven, add this repository definition to your `pom.xml`:

```xml
<repository>
  <id>clojars.org</id>
  <url>http://clojars.org/repo</url>
</repository>
```

Then add the artifact as a dependency:

```xml
<dependency>
  <groupId>circleci</groupId>
  <artifactId>analytics-clj</artifactId>
  <version>0.8.0</version>
</dependency>
```

Or, if you're using Leiningen:

```clj
[circleci/analytics-clj "0.8.0"]
```

You only need to initialize once at the start of your program. You can then keep
using the `Analytics` singleton anywhere in your code.

```clj
(use '[circleci.analytics-clj.core])
(def analytics (initialize "<writeKey>"))
```

The default initialization settings are production-ready.

### Regional configuration

For Business plans with access to [Regional Segment](/docs/segment/guides/regional-segment), you can use the `host` configuration parameter to send data to the desired region:

1. Oregon (Default) — `api.segment.io/`
2. Dublin — `events.eu1.segmentapis.com/`

## Identify

Identify calls let you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about them.

Segment recommends calling Identify a single time when the user's account is first created, and only identifying again later when their traits change.

Example Identify call:

```clj
(identify analytics "user-id" {:email "bob@acme.com"})
```

This call identifies the user by their unique User ID (the one you know them by in your database) and labeling them with an `email` trait.

The Identify call has the following fields:

| Field     | Data type       | Description                                                                         |
| --------- | --------------- | ----------------------------------------------------------------------------------- |
| `user-id` | *String*        | The ID for this user in your database.                                              |
| `traits`  | *Map, optional* | A map of traits you know about the user. Things like: `email`, `name` or `friends`. |

Find details on the Identify method payload in the [Segment Spec](/docs/segment/connections/spec/identify/).

## Track

Track calls let you record the actions your users perform. Every action triggers an event, which can also have associated properties.

You'll want to track events that are indicators of success for your site, like **Signed Up**, **Item Purchased** or **Article Bookmarked**.

To get started, Segment recommends tracking just a few important events. You can always add more later.

Example Track call:

```clj
(track analytics "user-id" "Signed Up" {:plan "trial"})
```

```clj
(track analytics (:id user) "signup" {:company "Acme Inc."} {:context {:language "en-us"}
   :integrations {"AdRoll" false}
   :integration-options {"Amplitude" {:session-id (:id session)}}})
```

This example Track call tells you that your user just triggered the **Signed Up** event on a "trial" plan.

Track event properties can be anything you want to record. In this case, one property is plan type.

The Track call has the following fields:

| Field        | Data type       | Description                                                                                                                |
| ------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `user-id`    | *String*        | The ID for this user in your database.                                                                                     |
| `event`      | *String*        | The name of the event you're tracking. Segment recommends human-readable names like **Song Played** or **Status Updated**. |
| `properties` | *Map, optional* | A map of properties for the event. If the event was **Added to Cart**, it might have properties like `price` or `product`. |

Find details on best practices in event naming and the Track method payload in the [Segment Spec](/docs/segment/connections/spec/track/).

## Group

Group lets you associate an [identified user](/docs/segment/connections/sources/catalog/libraries/server/java/#identify) user with a group. A group could be a company, organization, account, project or team. It also lets you record custom traits about the group, like industry or number of employees.

This is useful for tools like [Intercom](/docs/segment/connections/destinations/catalog/intercom/), [Preact](/docs/segment/connections/destinations/catalog/preact/) and [Totango](/docs/segment/connections/destinations/catalog/totango/), as it ties the user to a **group** of other users.

```clj
(group analytics "1234" "group-5678" {:name "Segment"})
```

The Group call has the following fields:

| Field     | Data type          | Description                                                                        |
| --------- | ------------------ | ---------------------------------------------------------------------------------- |
| `userId`  | *String*           | The ID for this user in your database.                                             |
| `groupId` | *String*           | The ID for this group in your database.                                            |
| `traits`  | *Traits, optional* | A dictionary of traits you know about the group. Things like: `name` or `website`. |

Find more details about Group, including the **Group payload**, in the [Segment Spec](/docs/segment/connections/spec/group/).

## Screen

The [Screen](/docs/segment/connections/spec/screen/) method lets you record whenever a user sees a screen of your mobile app, along with optional extra information about the page being viewed.

You'll want to record a Screen event whenever a user opens a screen in your app.

Not all services support Screen, so when it's not supported explicitly, the Screen method tracks as an event with the same parameters.

```clj
(screen analytics "1234" "Login" {:path "/users/login"})
```

A Screen call has the following fields:

| Field        | Data type              | Description                                                                                                                    |
| ------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `userId`     | *String*               | The ID for this user in your database.                                                                                         |
| `name`       | *String*               | The webpage name you're tracking. Segment recommends human-readable names like **Login** or **Register**.                      |
| `properties` | *Properties, optional* | A dictionary of properties for the webpage visit. If the event was **Login**, it might have properties like `path` or `title`. |

## Alias

Alias is how you associate one identity with another. This is an advanced method, but it is required to manage user identities successfully in *some* destinations.

In [Mixpanel](/docs/segment/connections/destinations/catalog/mixpanel/#alias), it's used to associate an anonymous user with an identified user once they sign up. For [Kissmetrics](/docs/segment/connections/destinations/catalog/kissmetrics/#alias), if your user switches IDs, you can use 'alias' to rename the 'userId'.

Example Alias call:

```clj
(alias analytics "user-id" "real-id")
```

For more details about Alias, including the **Alias call payload**, check out the [Segment Spec](/docs/segment/connections/spec/alias/).

## Builder

If the above methods don't meet your needs, you can use the builder types directly.

```clj
(enqueue analytics (doto (YourMessageType/builder)
 (.userId "user-id")
 (.properties {"company" "Acme Inc."})))
```

## Logging

You can set a custom logger on the client using the following code snippet:

```clj
(defn logger []
  (reify com.segment.analytics.Log
    (print [this level format args]
      (println (str (java.util.Date.) "\t" level "\t" args)))
    (print [this level error format args]
      (println error))))

(def analytics (initialize "<writeKey>" {:log (logger)}))
```

## Troubleshooting

The following tips often help resolve common issues.

#### No events in my debugger

1. Double check that you've set up the library correctly.
2. Make sure that you're calling one of Segment's API methods once the library is successfully installed, like [Identify](#identify) or [Track](#track).

### Other common errors

If you are experiencing data loss from your source, you may be experiencing one or more of the following common errors:

* **Payload is too large**: If you attempt to send events larger than 32KB per normal API request or batches of events larger than 500KB per request, Segment's tracking API responds with `400 Bad Request`. Try sending smaller events (or smaller batches) to correct this error.
* **Identifier is not present**: Segment's tracking API requires that each payload has a `userId` and/or `anonymousId`. If you send events without either the `userId` or `anonymousId`, Segment's tracking API responds with an `no_user_anon_id` error. Check the event payload and client instrumentation for more details.
* **Track event is missing name**: All Track events to Segment must have a name in string format.
* **Event dropped during deduplication**: Segment automatically adds a `messageId` field to all payloads and uses this value to deduplicate events. If you're manually setting a `messageId` value, ensure that each event has a unique value.
* **Incorrect credentials**: Double check your credentials for your downstream destination(s).
* **Destination incompatibility**: Make sure that the destination you are troubleshooting can accept server-side API calls. You can see compatibility information on the [Destination comparison by category](/docs/segment/connections/destinations/category-compare/) page and in the documentation for your specific destination.
* **Destination-specific requirements**: Check out the [destination's documentation](/docs/segment/connections/destinations/) to see if there are other requirements for using the method and destination that you're trying to get working.
