import { Table, Prerequisites } from "docs-ui"

export const metadata = {
  title: `Local Analytics Module Provider`,
}

# {metadata.title}

The Local Analytics Module Provider is a simple analytics provider for Medusa that logs analytics events to the console. It's useful for development and debugging purposes.

<Note>

The Analytics Module and its providers are available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).

</Note>

---

## Register the Local Analytics Module

Add the module into the `provider` object of the Analytics Module:

<Note>

You can use only one Analytics Module Provider in your Medusa application.

</Note>

```ts title="medusa-config.ts"
module.exports = defineConfig({
  // ...
  modules: [
    {
      resolve: "@medusajs/medusa/analytics",
      options: {
        providers: [
          {
            resolve: "@medusajs/analytics-local",
            id: "local",
          },
        ],
      },
    },
  ],
})
```

### Change Log Level

The Local Analytics Module Provider logs events to the console at the `debug` level, which is below the default `http` level.

So, to see the tracked events in your logs, you need to change the log level to `debug` or `silly`. You can do so by setting the `LOG_LEVEL` system environment variable:

```bash
export LOG_LEVEL=debug
```

<Note title="Important">

The environment variable must be set as a system environment variable and not in `.env`.

</Note>

---

## Test out the Module

To test the module out, you'll track in the console when an order is placed.

You'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event.

For example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:

export const workflowHighlights = [
  ["14", "resolve", "Resolve the Analytics Module's service"],
  ["16", "track", "Track the event in the installed Analytics Module Provider"]
]

```ts title="src/workflows/track-order-placed.ts" highlights={workflowHighlights}
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"

type StepInput = {
  order: OrderDTO
}

const trackOrderPlacedStep = createStep(
  "track-order-placed-step",
  async ({ order }: StepInput, { container }) => {
    const analyticsModuleService = container.resolve(Modules.ANALYTICS)

    await analyticsModuleService.track({
      event: "order_placed",
      actor_id: order.customer_id,
      properties: {
        order_id: order.id,
        total: order.total,
        items: order.items?.map((item) => ({
          variant_id: item.variant_id,
          product_id: item.product_id,
          quantity: item.quantity,
        })),
        customer_id: order.customer_id,
      },
    })
  }
)

type WorkflowInput = {
  order_id: string
}

export const trackOrderPlacedWorkflow = createWorkflow(
  "track-order-placed-workflow",
  ({ order_id }: WorkflowInput) => {
    const { data: orders } = useQueryGraphStep({
      entity: "order",
      fields: [
        "*",
        "customer.*",
        "items.*",
      ],
      filters: {
        id: order_id,
      },
    })
    trackOrderCreatedStep({
      order: orders[0],
    } as unknown as StepInput)
  }
)
```

This workflow retrieves the order details using the `useQueryGraphStep` and then tracks the order placement event using the `trackOrderPlacedStep`.

In the step, you resolve the service of the Analytics Module from the [Medusa container](!docs!/learn/fundamentals/medusa-container) and use its `track` method to track the event. This method will use the underlying provider configured (which is the Local Analytics Module Provider, in this case) to track the event.

Next, create a subscriber at `src/subscribers/order-placed.ts` with the following content:

```ts title="src/subscribers/order-placed.ts"
import type {
  SubscriberArgs,
  SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderPlacedWorkflow } from "../workflows/track-order-placed"

export default async function orderPlacedHandler({
  event: { data },
  container,
}: SubscriberArgs<{ id: string }>) {
  await trackOrderPlacedWorkflow(container).run({
    input: {
      order_id: data.id,
    },
  })
}

export const config: SubscriberConfig = {
  event: "order.placed",
}
```

This subscriber listens to the `order.placed` event and executes the `trackOrderPlacedWorkflow` workflow, passing the order ID as input.

You'll now track the order placement event whenever an order is placed in your Medusa application. You can test this out by placing an order and checking the server's logs for the tracked event.

---

## Additional Resources

- [How to Use the Analytics Module](/references/analytics/service)