Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NodeJS and Attachment #4371

Closed
ErcinDedeoglu opened this issue Jan 5, 2022 · 20 comments
Closed

NodeJS and Attachment #4371

ErcinDedeoglu opened this issue Jan 5, 2022 · 20 comments
Labels
Package: node Issues related to the Sentry Node SDK

Comments

@ErcinDedeoglu
Copy link

ErcinDedeoglu commented Jan 5, 2022

Maybe it's not a bug, but I'm not sure. because there is no documentation for it.

We are trying to send an attachment of the issue to the sentry via the NodeJS backend application. I wrote the code below by commenting out the API, but it didn't work.

const sentryResponse = Sentry.captureException(err.original);
const client = Sentry.getCurrentHub().getClient();
const { host, path, projectId, port, protocol, user } = client.getDsn();
const endpoint = ${protocol}://${host}${port !== '' ? :${port}: ''}${ path !== '' ?/${path} : '' }/api/${projectId}/events/${sentryResponse}/attachments/?sentry_key=${user}&sentry_version=7&sentry_client=custom-javascript;

fetch(endpoint, {
  method: 'POST',
  body: {
    'variables.file': fs.createReadStream('./README.md')
  },
}).catch((ex) => {
  // we have to catch this otherwise it throws an infinite loop in Sentry
  console.error(ex);
});

} catch (ex) {
console.error(ex);
}

There has to be a simpler way to do this?

@AbhiPrasad
Copy link
Member

Hey thanks for writing in! There is currently no first class support for attachments in the JavaScript SDK, but we are working on implementing it soon.

For now, you can attach attachments in beforeSend (grabbing the event id that way). If it's still not working - could you provide a minimal reproduction of your set up + sentry config? That will help us debug.

@AbhiPrasad AbhiPrasad added Package: node Issues related to the Sentry Node SDK Status: Needs Information and removed Type: Question labels Jan 10, 2022
@github-actions
Copy link
Contributor

This issue has gone three weeks without activity. In another week, I will close it.

But! If you comment or otherwise update it, I will reset the clock, and if you label it Status: Backlog or Status: In Progress, I will leave it alone ... forever!


"A weed is but an unloved flower." ― Ella Wheeler Wilcox 🥀

@kldavis4
Copy link

kldavis4 commented Feb 1, 2022

Example: https://github.com/kldavis4/sentry_nodejs_attachments_example

@yousefa00
Copy link

yousefa00 commented May 9, 2022

Any idea why this might not be working for me? I have the following Sentry configuration:

const attachmentUrlFromDsn = (dsn: DsnComponents, eventId: string) => {
  const { host, path, projectId, port, protocol, user } = dsn
  return `${protocol}://${host}${port !== '' ? `:${port}` : ''}${
    path !== '' ? `/${path}` : ''
  }/api/${projectId}/events/${eventId}/attachments/?sentry_key=${user}&sentry_version=7&sentry_client=custom-javascript`
}

export const attachAsJson = async (
  attachments: string[],
  event: Sentry.Event,
  client: any
) => {
  const dsn = client?.getDsn()

  if (!dsn || !event.event_id) {
    return
  }

  const endpoint = attachmentUrlFromDsn(dsn, event.event_id)
  logger.info(endpoint)

  const formData = new FormData()
  for (const attachment of attachments) {
    formData.append('attachments', attachment)
  }
  logger.info(formData)

  try {
    await axios.request({
      method: 'POST',
      url: endpoint,
      data: formData,
      headers: {
        'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`
      }
    })
    return event
  } catch (err) {
    logger.error(err)
    return null
  }
}

And include this where the attachment is in scope:

Sentry.addGlobalEventProcessor(async event => {
    try {
      const client = Sentry.getCurrentHub().getClient()
      if (!client) {
        return null
      }
      await attachAsJson([attachment], event, client)
    } catch (ex) {
      logger.error(ex)
    }
    return event
  })

I see the Sentry events created correctly, and logging the API request status code is 201, yet there are no attachments on the actual event created. Any help would be greatly appreciated.

@pkaminski
Copy link
Contributor

I have a similar problem to @yousefa00. I adapted @kldavis4's code above and get a 201 Created when uploading the attachment, but nothing shows up in Sentry on the attachments tab. One difference is that I grab the event ID from the return value of Sentry.captureException rather than in beforeSend or an event processor, but I don't imagine that ought to matter.

Can any from Sentry speculate on what might be going wrong given that no errors pop up at any point during the process? If it helps trace things, one such recent event was 4ec36c5f7ed14ca69ea40d9c50487390. Thanks!

@kldavis4
Copy link

I did open a support ticket for this and asked

"Are attachments in nodejs sdk planned? What's the recommended solution/workaround for this? It doesn't really make intuitive sense that this would work in the javascript sdk but not the nodejs sdk."

and the reply was:

"I don't have any specific roadmap info for attachments to be added for the Node SDK, and unfortunately, there isn't an available work around. Events that are processed from the Node SDK don't support adding event attachments."

I still believe it should be possible to make this work (somehow), but this response makes me believe Sentry is intentionally preventing this.

@pkaminski
Copy link
Contributor

Arrgh. That's frustrating, but at least now I know we need to build our own workaround and there's no point in upgrading to Sentry's "Performance" tier. Thanks!

@lforst
Copy link
Member

lforst commented May 24, 2022

Hi, we're adding support for attachments in v7 of the SDK (#5004). We're providing a release candidate for that version in the upcoming days. Feel free to try it out and report back whether it fits your needs.

@lforst
Copy link
Member

lforst commented Jun 1, 2022

Happy to announce that we released the Attachments API with v7! Please see https://docs.sentry.io/platforms/javascript/enriching-events/attachments/ on how to use it.

Closing this for now. Feel free to ping me here if there are any questions!

@lforst lforst closed this as completed Jun 1, 2022
@aspala
Copy link

aspala commented Jun 15, 2022

Hello @lforst

This seems to still be missing/not functioning in the node implementation (7.1.1).

Adding attachments via

Sentry.configureScope(scope => {
  scope.addAttachment({ filename: "attachment.txt", data: "Some content" });
});

will add the corresponding entry within the hint. (this can be verified by adding a addGlobalEventProcessor and inspecting the hint).
Attachments "uploaded" this way will not show up in the sentry-UI.

Strangely: using the approach @yousefa00 used will yield a 201 Created status, but even then the attachments will not show up within the sentry UI. Note: The above approach is outdated, as it uses the user prop returned from dsn (DsnComponents), which now should be replaced by the publicKey i guess:

  function attachmentUrlFromDsn(dsn, eventId) {
    const { host, path, projectId, port, protocol, publicKey } = dsn;
    return `${protocol}://${host}${port !== '' ? `:${port}` : ''}${
      path !== '' ? `/${path}` : ''
    }/api/${projectId}/events/${eventId}/attachments/?sentry_key=${publicKey}&sentry_version=7&sentry_client=custom-javascript`;
  }

}

Question:
Can you verify, whether uploading attachments via the node (@sentry/node) package works as intended?

Thank you for your time and involvement in this matter.

@AbhiPrasad
Copy link
Member

const Sentry = require('@sentry/node');

async function run() {
  Sentry.init({
    debug: true,
    dsn: process.env.SENTRY_DSN,
  });
  
  Sentry.configureScope(scope => {
    scope.addAttachment({ filename: "attachment.txt", data: "some context" })
  });
  
  Sentry.captureException(new Error('me'));
  
  await Sentry.flush(2000);
}

run();

With the following example I was able to get attachments on all my events.

image

Could you open up a new GH issue with some kind of reproduction or details of you Sentry.init so we can further investigate @aspala?

@aspala
Copy link

aspala commented Jun 22, 2022

@AbhiPrasad i opened an issue and provided reproduction steps
I identified two variables which may be the cause of the issue.
a) i am using module syntax (business-requirement, nothing i can change easily)
b) our sentry account is the bare-minimum tier (Small plan, 100K errors)

Are there requirements regarding the account (tiers, or features we need to pay for?) when using attachments?

@WeeJeWel
Copy link

WeeJeWel commented Jan 2, 2023

Unfortunately I am unable to add attachments using Node.js on the Team plan: getsentry/sentry-docs#5195 (comment)

@lforst
Copy link
Member

lforst commented Jan 3, 2023

@WeeJeWel Can you share a link to the Sentry event that doesn't have the attachment? Thanks!

@lforst
Copy link
Member

lforst commented Jan 3, 2023

@WeeJeWel It seems like the Sentry backend hasn't seen or dropped any attachments. Could you check if there is any suspicious output when setting debug: true in Sentry.init()?

@WeeJeWel
Copy link

WeeJeWel commented Jan 3, 2023

I've already tested with debug: true but didn't see any debug messages when Sentry.captureException was called. Only after Sentry.init().

@WeeJeWel
Copy link

WeeJeWel commented Jan 3, 2023

I've already tested with debug: true but didn't see any debug messages when Sentry.captureException was called. Only after Sentry.init().

But the exception was created so it did do something.

@lforst
Copy link
Member

lforst commented Jan 5, 2023

@WeeJeWel Can you provide a small reproduction example so we can debug this further? Thanks!

@WeeJeWel
Copy link

WeeJeWel commented Jan 5, 2023

See the other post.

But this fixed it:

Sentry.configureScope(scope => {
 scope.addAttachment({
  filename: 'coredump.txt',
  data: '...', // about 18kb string, doesn't work
  contentType: 'text/plain',
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Package: node Issues related to the Sentry Node SDK
Projects
None yet
Development

No branches or pull requests

9 participants