# Better Stack Koa client

## Start logging in 3 steps

### 1. Install

Install Logtail Koa NPM package:

```bash
[label Install Logtail Koa]
npm install @logtail/koa
```

### 2. Setup

Set up Logtail client and attach it to Koa instance:

```javascript
[label Attach Logtail to Koa]
const Koa = require("koa");
const { Logtail } = require("@logtail/koa");

// Create new Koa instance
const koa = new Koa();

// Create new Logtail client
const logtail = new Logtail("$SOURCE_TOKEN", {
  endpoint: 'https://$INGESTING_HOST',
});

// Attach Koa to enable HTTP request logging
logtail.attach(koa);
```



### 3. Start logging 🎉

All HTTP requests handled by Koa will be logged and sent to Better Stack.

Ensure that all logs are sent to Logtail:
  
```javascript
[label Send logs to Logtail]
logtail.flush()
```

You should see your logs in [Logtail → Live tail](https://logtail.com/team/0/tail ";_blank").

[warning]
**Koa version 2.6.2 or higher is required.**
[/warning]

## Need help?

Please let us know at hello@betterstack.com.  
We're happy to help! 🙏

## Additional information

### How the middleware works

#### Successful requests

Successful requests end with a `2xx` or `3xx` status codes and do not throw any errors. They are logged to Logtail using [Info log level](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel).

#### 4xx status codes

Requests with `4xx` status codes are considered warnings. Such requests are logged to Logtail with [Warn log level](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel).

#### 5xx status codes

Requests with `5xx` status codes are considered errors. Such requests are logged to Logtail with [Error log level](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel).

#### Uncaught errors

Unhandled errors are caught by Logtail middleware. The errors are logged to Logtail with [Error log level](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel).


### Additional logging

With Logtail Koa client you can use `debug()`, `info()`, `warn()`, and `error()` methods just like with [Logtail JavaScript client](https://betterstack.com/docs/logs/javascript/logging/).
